| 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-2025 Valentin Samir |
| 12 |
"""Tests module for views""" |
| 13 |
from cas_server.default_settings import settings |
| 14 |
|
| 15 |
import django |
| 16 |
from django.test import TestCase, Client |
| 17 |
from django.test.utils import override_settings |
| 18 |
from django.utils import timezone |
| 19 |
|
| 20 |
|
| 21 |
import random |
| 22 |
import json |
| 23 |
from unittest import mock |
| 24 |
from lxml import etree |
| 25 |
|
| 26 |
from cas_server import models |
| 27 |
from cas_server import utils |
| 28 |
from cas_server.tests.utils import ( |
| 29 |
copy_form, |
| 30 |
get_login_page_params, |
| 31 |
get_auth_client, |
| 32 |
get_user_ticket_request, |
| 33 |
get_pgt, |
| 34 |
get_proxy_ticket, |
| 35 |
get_validated_ticket, |
| 36 |
HttpParamsHandler, |
| 37 |
Http404Handler |
| 38 |
) |
| 39 |
from cas_server.tests.mixin import BaseServicePattern, XmlContent, CanLogin |
| 40 |
|
| 41 |
|
| 42 |
@override_settings(CAS_AUTH_CLASS='cas_server.auth.TestAuthUser') |
| 43 |
class LoginTestCase(TestCase, BaseServicePattern, CanLogin): |
| 44 |
"""Tests for the login view""" |
| 45 |
def setUp(self): |
| 46 |
"""Prepare the test context:""" |
| 47 |
# we prepare a bunch a service url and service patterns for tests |
| 48 |
self.setup_service_patterns() |
| 49 |
|
| 50 |
@override_settings(CAS_NEW_VERSION_HTML_WARNING=True) |
| 51 |
@mock.patch("cas_server.utils.last_version", lambda: "1.2.3") |
| 52 |
@mock.patch("cas_server.utils.VERSION", "0.1.2") |
| 53 |
def test_new_version_available_ok(self): |
| 54 |
"""test the new version info box""" |
| 55 |
client = Client() |
| 56 |
response = client.get("/login") |
| 57 |
self.assertIn(b"A new version of the application is available", response.content) |
| 58 |
|
| 59 |
@override_settings(CAS_NEW_VERSION_HTML_WARNING=True) |
| 60 |
@mock.patch("cas_server.utils.last_version", lambda: None) |
| 61 |
@mock.patch("cas_server.utils.VERSION", "0.1.2") |
| 62 |
def test_new_version_available_badpypi(self): |
| 63 |
""" |
| 64 |
test the new version info box if pypi is not available (unable to retreive last version) |
| 65 |
""" |
| 66 |
client = Client() |
| 67 |
response = client.get("/login") |
| 68 |
self.assertNotIn(b"A new version of the application is available", response.content) |
| 69 |
|
| 70 |
@override_settings(CAS_NEW_VERSION_HTML_WARNING=False) |
| 71 |
def test_new_version_available_disabled(self): |
| 72 |
"""test the new version info box is disabled""" |
| 73 |
client = Client() |
| 74 |
response = client.get("/login") |
| 75 |
self.assertNotIn(b"A new version of the application is available", response.content) |
| 76 |
|
| 77 |
@override_settings(CAS_INFO_MESSAGES_ORDER=["cas_explained"]) |
| 78 |
def test_messages_info_box_enabled(self): |
| 79 |
"""test that the message info-box is displayed then enabled""" |
| 80 |
client = Client() |
| 81 |
response = client.get("/login") |
| 82 |
self.assertIn( |
| 83 |
b"The Central Authentication Service grants you access to most of our websites by ", |
| 84 |
response.content |
| 85 |
) |
| 86 |
|
| 87 |
@override_settings(CAS_INFO_MESSAGES_ORDER=[]) |
| 88 |
def test_messages_info_box_disabled(self): |
| 89 |
"""test that the message info-box is not displayed then disabled""" |
| 90 |
client = Client() |
| 91 |
response = client.get("/login") |
| 92 |
self.assertNotIn( |
| 93 |
b"The Central Authentication Service grants you access to most of our websites by ", |
| 94 |
response.content |
| 95 |
) |
| 96 |
|
| 97 |
# test1 and test2 are malformed and should be ignored, test3 is ok, test5 do not |
| 98 |
# exists and should be ignored |
| 99 |
@override_settings(CAS_INFO_MESSAGES_ORDER=["test1", "test2", "test3", "test5"]) |
| 100 |
@override_settings(CAS_INFO_MESSAGES={ |
| 101 |
"test1": "test", # not a dict, should be ignored |
| 102 |
"test2": {"type": "success"}, # not "message" key, should be ignored |
| 103 |
"test3": {"message": "test3"}, |
| 104 |
"test4": {"message": "test4"}, |
| 105 |
}) |
| 106 |
def test_messages_info_box_bad_messages(self): |
| 107 |
"""test that mal formated messages dict are ignored""" |
| 108 |
client = Client() |
| 109 |
# not errors should be raises |
| 110 |
response = client.get("/login") |
| 111 |
# test3 is ok est should be there |
| 112 |
self.assertIn(b"test3", response.content) |
| 113 |
# test4 is not in CAS_INFO_MESSAGES_ORDER and should not be there |
| 114 |
self.assertNotIn(b"test4", response.content) |
| 115 |
|
| 116 |
def test_login_view_post_goodpass_goodlt(self): |
| 117 |
"""Test a successul login""" |
| 118 |
# we get a client who fetch a frist time the login page and the login form default |
| 119 |
# parameters |
| 120 |
client, params = get_login_page_params() |
| 121 |
# we set username/password in the form |
| 122 |
params["username"] = settings.CAS_TEST_USER |
| 123 |
params["password"] = settings.CAS_TEST_PASSWORD |
| 124 |
# the LoginTicket in the form should match a valid LT in the user session |
| 125 |
self.assertTrue(params['lt'] in client.session['lt']) |
| 126 |
|
| 127 |
# we post a login attempt |
| 128 |
response = client.post('/login', params) |
| 129 |
# as username/password/lt are all valid, the login should succed |
| 130 |
self.assert_logged(client, response) |
| 131 |
# The LoginTicket is conssumed and should no longer be valid |
| 132 |
self.assertTrue(params['lt'] not in client.session['lt']) |
| 133 |
|
| 134 |
def test_login_post_missing_params(self): |
| 135 |
"""Test a login attempt with missing POST parameters (username or password or both)""" |
| 136 |
# we get a client who fetch a frist time the login page and the login form default |
| 137 |
# parameters |
| 138 |
client, params = get_login_page_params() |
| 139 |
# we set only set username |
| 140 |
params["username"] = settings.CAS_TEST_USER |
| 141 |
# we post a login attempt |
| 142 |
response = client.post('/login', params) |
| 143 |
# as the LT is not valid, login should fail |
| 144 |
self.assert_login_failed(client, response) |
| 145 |
|
| 146 |
# we get a client who fetch a frist time the login page and the login form default |
| 147 |
# parameters |
| 148 |
client, params = get_login_page_params() |
| 149 |
# we set only set password |
| 150 |
params["password"] = settings.CAS_TEST_PASSWORD |
| 151 |
# we post a login attempt |
| 152 |
response = client.post('/login', params) |
| 153 |
# as the LT is not valid, login should fail |
| 154 |
self.assert_login_failed(client, response) |
| 155 |
|
| 156 |
# we get a client who fetch a frist time the login page and the login form default |
| 157 |
# parameters |
| 158 |
client, params = get_login_page_params() |
| 159 |
# we set neither username nor password |
| 160 |
# we post a login attempt |
| 161 |
response = client.post('/login', params) |
| 162 |
# as the LT is not valid, login should fail |
| 163 |
self.assert_login_failed(client, response) |
| 164 |
|
| 165 |
def test_login_view_post_goodpass_goodlt_warn(self): |
| 166 |
"""Test a successul login requesting to be warned before creating services tickets""" |
| 167 |
# get a client and initial login params |
| 168 |
client, params = get_login_page_params() |
| 169 |
# set valids usernames/passswords |
| 170 |
params["username"] = settings.CAS_TEST_USER |
| 171 |
params["password"] = settings.CAS_TEST_PASSWORD |
| 172 |
# this time, we check the warn checkbox |
| 173 |
params["warn"] = "on" |
| 174 |
|
| 175 |
# postings login request |
| 176 |
response = client.post('/login', params) |
| 177 |
# as username/password/lt are all valid, the login should succed and warn be enabled |
| 178 |
self.assert_logged(client, response, warn=True) |
| 179 |
|
| 180 |
def test_lt_max(self): |
| 181 |
"""Check we only keep the last 100 Login Ticket for a user""" |
| 182 |
# get a client and initial login params |
| 183 |
client, params = get_login_page_params() |
| 184 |
# get a first LT that should be valid |
| 185 |
current_lt = params["lt"] |
| 186 |
# we keep the last 100 generated LT by user, so after having generated `i_in_test` we |
| 187 |
# test if `current_lt` is still valid |
| 188 |
i_in_test = random.randint(0, 99) |
| 189 |
# after `i_not_in_test` `current_lt` should be valid not more |
| 190 |
i_not_in_test = random.randint(101, 150) |
| 191 |
# start generating 150 LT |
| 192 |
for i in range(150): |
| 193 |
if i == i_in_test: |
| 194 |
# before more than 100 LT generated, the first TL should be valid |
| 195 |
self.assertTrue(current_lt in client.session['lt']) |
| 196 |
if i == i_not_in_test: |
| 197 |
# after more than 100 LT generated, the first LT should be valid no more |
| 198 |
self.assertTrue(current_lt not in client.session['lt']) |
| 199 |
# assert that we do not keep more that 100 valid LT |
| 200 |
self.assertTrue(len(client.session['lt']) <= 100) |
| 201 |
# generate a new LT by getting the login page |
| 202 |
client, params = get_login_page_params(client) |
| 203 |
# in the end, we still have less that 100 valid LT |
| 204 |
self.assertTrue(len(client.session['lt']) <= 100) |
| 205 |
|
| 206 |
def test_login_view_post_badlt(self): |
| 207 |
"""Login attempt with a bad LoginTicket, login should fail""" |
| 208 |
# get a client and initial login params |
| 209 |
client, params = get_login_page_params() |
| 210 |
# set valid username/password |
| 211 |
params["username"] = settings.CAS_TEST_USER |
| 212 |
params["password"] = settings.CAS_TEST_PASSWORD |
| 213 |
# set a bad LT |
| 214 |
params["lt"] = 'LT-random' |
| 215 |
|
| 216 |
# posting the login request |
| 217 |
response = client.post('/login', params) |
| 218 |
|
| 219 |
# as the LT is not valid, login should fail |
| 220 |
self.assert_login_failed(client, response) |
| 221 |
# the reason why login has failed is displayed to the user |
| 222 |
self.assertTrue(b"Invalid login ticket" in response.content) |
| 223 |
|
| 224 |
def test_login_view_post_badpass_good_lt(self): |
| 225 |
"""Login attempt with a bad password""" |
| 226 |
# get a client and initial login params |
| 227 |
client, params = get_login_page_params() |
| 228 |
# set valid username but invalid password |
| 229 |
params["username"] = settings.CAS_TEST_USER |
| 230 |
params["password"] = "test2" |
| 231 |
# posting the login request |
| 232 |
response = client.post('/login', params) |
| 233 |
|
| 234 |
# as the password is wrong, login should fail |
| 235 |
self.assert_login_failed(client, response) |
| 236 |
# the reason why login has failed is displayed to the user |
| 237 |
self.assertTrue( |
| 238 |
( |
| 239 |
b"The credentials you provided cannot be " |
| 240 |
b"determined to be authentic" |
| 241 |
) in response.content |
| 242 |
) |
| 243 |
|
| 244 |
def assert_ticket_attributes(self, client, ticket_value): |
| 245 |
"""check the ticket attributes in the db""" |
| 246 |
# Get get current session user in the db |
| 247 |
user = models.User.objects.get( |
| 248 |
username=settings.CAS_TEST_USER, |
| 249 |
session_key=client.session.session_key |
| 250 |
) |
| 251 |
# we should find exactly one user |
| 252 |
self.assertTrue(user) |
| 253 |
# get the ticker object corresponting to `ticket_value` |
| 254 |
ticket = models.ServiceTicket.objects.get(value=ticket_value) |
| 255 |
# chek that the ticket is well attributed to the user |
| 256 |
self.assertEqual(ticket.user, user) |
| 257 |
# check that the user attributes match the attributes registered on the ticket |
| 258 |
self.assertEqual(ticket.attributs, settings.CAS_TEST_ATTRIBUTES) |
| 259 |
# check that the ticket has not being validated yet |
| 260 |
self.assertEqual(ticket.validate, False) |
| 261 |
# check that the service pattern registered on the ticket is the on we use for tests |
| 262 |
self.assertEqual(ticket.service_pattern, self.service_pattern) |
| 263 |
|
| 264 |
def assert_service_ticket(self, client, response, service="https://www.example.com"): |
| 265 |
"""check that a ticket is well emited when requested on a allowed service""" |
| 266 |
# On ticket emission, we should be redirected to the service url, setting the ticket |
| 267 |
# GET parameter |
| 268 |
self.assertEqual(response.status_code, 302) |
| 269 |
self.assertTrue(response.has_header('Location')) |
| 270 |
self.assertTrue( |
| 271 |
response['Location'].startswith( |
| 272 |
"%s?ticket=%s-" % (service, settings.CAS_SERVICE_TICKET_PREFIX) |
| 273 |
) |
| 274 |
) |
| 275 |
# check that the value of the ticket GET parameter match the value of the ticket |
| 276 |
# created in the db |
| 277 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 278 |
self.assert_ticket_attributes(client, ticket_value) |
| 279 |
|
| 280 |
def test_view_login_get_allowed_service(self): |
| 281 |
"""Request a ticket for an allowed service by an unauthenticated client""" |
| 282 |
# get a bare new http client |
| 283 |
client = Client() |
| 284 |
# we are not authenticated and are asking for a ticket for https://www.example.com |
| 285 |
# which is a valid service matched by self.service_pattern |
| 286 |
response = client.get("/login?service=https://www.example.com") |
| 287 |
# the login page should be displayed |
| 288 |
self.assertEqual(response.status_code, 200) |
| 289 |
# we warn the user why it need to authenticated |
| 290 |
self.assertTrue( |
| 291 |
( |
| 292 |
b"Authentication required by service " |
| 293 |
b"example (https://www.example.com)" |
| 294 |
) in response.content |
| 295 |
) |
| 296 |
|
| 297 |
@override_settings(CAS_SHOW_SERVICE_MESSAGES=False) |
| 298 |
def test_view_login_get_allowed_service_no_message(self): |
| 299 |
"""Request a ticket for an allowed service by an unauthenticated client""" |
| 300 |
# get a bare new http client |
| 301 |
client = Client() |
| 302 |
# we are not authenticated and are asking for a ticket for https://www.example.com |
| 303 |
# which is a valid service matched by self.service_pattern |
| 304 |
response = client.get("/login?service=https://www.example.com") |
| 305 |
# the login page should be displayed |
| 306 |
self.assertEqual(response.status_code, 200) |
| 307 |
# we warn the user why it need to authenticated |
| 308 |
self.assertFalse( |
| 309 |
( |
| 310 |
b"Authentication required by service " |
| 311 |
b"example (https://www.example.com)" |
| 312 |
) in response.content |
| 313 |
) |
| 314 |
|
| 315 |
def test_view_login_get_denied_service(self): |
| 316 |
"""Request a ticket for an denied service by an unauthenticated client""" |
| 317 |
# get a bare new http client |
| 318 |
client = Client() |
| 319 |
# we are not authenticated and are asking for a ticket for https://www.example.net |
| 320 |
# which is NOT a valid service |
| 321 |
response = client.get("/login?service=https://www.example.net") |
| 322 |
self.assertEqual(response.status_code, 200) |
| 323 |
# we warn the user that https://www.example.net is not an allowed service url |
| 324 |
self.assertTrue(b"Service https://www.example.net not allowed" in response.content) |
| 325 |
|
| 326 |
@override_settings(CAS_SHOW_SERVICE_MESSAGES=False) |
| 327 |
def test_view_login_get_denied_service_no_message(self): |
| 328 |
"""Request a ticket for an denied service by an unauthenticated client""" |
| 329 |
# get a bare new http client |
| 330 |
client = Client() |
| 331 |
# we are not authenticated and are asking for a ticket for https://www.example.net |
| 332 |
# which is NOT a valid service |
| 333 |
response = client.get("/login?service=https://www.example.net") |
| 334 |
self.assertEqual(response.status_code, 200) |
| 335 |
# we warn the user that https://www.example.net is not an allowed service url |
| 336 |
self.assertFalse(b"Service https://www.example.net not allowed" in response.content) |
| 337 |
|
| 338 |
def test_view_login_get_auth_allowed_service(self): |
| 339 |
""" |
| 340 |
Request a ticket for an allowed service by an authenticated client containing |
| 341 |
non ascii char in url |
| 342 |
""" |
| 343 |
# get a client that is already authenticated |
| 344 |
client = get_auth_client() |
| 345 |
# ask for a ticket for https://www.example.com |
| 346 |
response = client.get("/login?service=https://www.example.com/é") |
| 347 |
# as https://www.example.com/é is a valid service a ticket should be created and the |
| 348 |
# user redirected to the service url |
| 349 |
self.assert_service_ticket(client, response, service="https://www.example.com/%C3%A9") |
| 350 |
|
| 351 |
def test_view_login_get_auth_allowed_service_non_ascii(self): |
| 352 |
"""Request a ticket for an allowed service by an authenticated client""" |
| 353 |
# get a client that is already authenticated |
| 354 |
client = get_auth_client() |
| 355 |
# ask for a ticket for https://www.example.com |
| 356 |
response = client.get("/login?service=https://www.example.com") |
| 357 |
# as https://www.example.com is a valid service a ticket should be created and the |
| 358 |
# user redirected to the service url |
| 359 |
self.assert_service_ticket(client, response) |
| 360 |
|
| 361 |
def test_view_login_get_auth_allowed_service_warn(self): |
| 362 |
"""Request a ticket for an allowed service by an authenticated client""" |
| 363 |
# get a client that is already authenticated and has ask to be warned befor we |
| 364 |
# generated a ticket |
| 365 |
client = get_auth_client(warn="on") |
| 366 |
# ask for a ticket for https://www.example.com |
| 367 |
response = client.get("/login?service=https://www.example.com") |
| 368 |
# we display a warning to the user, asking him to validate the ticket creation (insted |
| 369 |
# a generating and redirecting directly to the service url) |
| 370 |
self.assertEqual(response.status_code, 200) |
| 371 |
self.assertTrue( |
| 372 |
( |
| 373 |
b"Authentication has been required by service " |
| 374 |
b"example (https://www.example.com)" |
| 375 |
) in response.content |
| 376 |
) |
| 377 |
# get the displayed form parameters |
| 378 |
params = copy_form(response.context["form"]) |
| 379 |
# we post, confirming we want a ticket |
| 380 |
response = client.post("/login", params) |
| 381 |
# as https://www.example.com is a valid service a ticket should be created and the |
| 382 |
# user redirected to the service url |
| 383 |
self.assert_service_ticket(client, response) |
| 384 |
|
| 385 |
def test_view_login_get_auth_denied_service(self): |
| 386 |
"""Request a ticket for a not allowed service by an authenticated client""" |
| 387 |
# get a client that is already authenticated |
| 388 |
client = get_auth_client() |
| 389 |
# we are authenticated and are asking for a ticket for https://www.example.org |
| 390 |
# which is NOT a valid service |
| 391 |
response = client.get("/login?service=https://www.example.org") |
| 392 |
self.assertEqual(response.status_code, 200) |
| 393 |
# we warn the user that https://www.example.net is not an allowed service url |
| 394 |
# NO ticket are created |
| 395 |
self.assertTrue(b"Service https://www.example.org not allowed" in response.content) |
| 396 |
|
| 397 |
def test_user_logged_not_in_db(self): |
| 398 |
"""If the user is logged but has been delete from the database, it should be logged out""" |
| 399 |
# get a client that is already authenticated |
| 400 |
client = get_auth_client() |
| 401 |
# delete the user in the db |
| 402 |
models.User.objects.get( |
| 403 |
username=settings.CAS_TEST_USER, |
| 404 |
session_key=client.session.session_key |
| 405 |
).delete() |
| 406 |
# fetch the login page |
| 407 |
response = client.get("/login") |
| 408 |
|
| 409 |
# The user should be logged out |
| 410 |
self.assert_login_failed(client, response, code=302) |
| 411 |
# and redirected to the login page. We branch depending on the version a django as |
| 412 |
# the test client behaviour changed after django 1.9 |
| 413 |
if django.VERSION < (1, 9): # pragma: no cover coverage is computed with dango 1.9 |
| 414 |
self.assertEqual(response["Location"], "http://testserver/login") |
| 415 |
else: |
| 416 |
self.assertEqual(response["Location"], "/login?") |
| 417 |
|
| 418 |
def test_service_restrict_user(self): |
| 419 |
"""Testing the restric user capability from a service""" |
| 420 |
# get a client that is already authenticated |
| 421 |
client = get_auth_client() |
| 422 |
|
| 423 |
# trying to get a ticket from a service url matched by a service pattern having a |
| 424 |
# restriction on the usernames allowed to get tickets. the test user username is not one |
| 425 |
# of this username. |
| 426 |
response = client.get("/login", {'service': self.service_restrict_user_fail}) |
| 427 |
self.assertEqual(response.status_code, 200) |
| 428 |
# the ticket is not created and a warning is displayed to the user |
| 429 |
self.assertTrue(b"Username not allowed" in response.content) |
| 430 |
|
| 431 |
# same but with the tes user username being one of the allowed usernames |
| 432 |
response = client.get("/login", {'service': self.service_restrict_user_success}) |
| 433 |
# the ticket is created and we are redirected to the service url |
| 434 |
self.assertEqual(response.status_code, 302) |
| 435 |
self.assertTrue( |
| 436 |
response["Location"].startswith("%s?ticket=" % self.service_restrict_user_success) |
| 437 |
) |
| 438 |
|
| 439 |
def test_service_filter(self): |
| 440 |
"""Test the filtering on user attributes""" |
| 441 |
# get a client that is already authenticated |
| 442 |
client = get_auth_client() |
| 443 |
|
| 444 |
# trying to get a ticket from a service url matched by a service pattern having |
| 445 |
# a restriction on the user attributes. The test user if ailing these restrictions |
| 446 |
# We try first with a single value attribut (aka a string) and then with |
| 447 |
# a multi values attributs (aka a list of strings) |
| 448 |
for service in [self.service_filter_fail, self.service_filter_fail_alt]: |
| 449 |
response = client.get("/login", {'service': service}) |
| 450 |
# the ticket is not created and a warning is displayed to the user |
| 451 |
self.assertEqual(response.status_code, 200) |
| 452 |
self.assertTrue(b"User characteristics not allowed" in response.content) |
| 453 |
|
| 454 |
# same but with rectriction that a valid upon the test user attributes |
| 455 |
response = client.get("/login", {'service': self.service_filter_success}) |
| 456 |
# the ticket us created and the user redirected to the service url |
| 457 |
self.assertEqual(response.status_code, 302) |
| 458 |
self.assertTrue(response["Location"].startswith("%s?ticket=" % self.service_filter_success)) |
| 459 |
|
| 460 |
def test_service_user_field(self): |
| 461 |
"""Test using a user attribute as username: case on if the attribute exists or not""" |
| 462 |
# get a client that is already authenticated |
| 463 |
client = get_auth_client() |
| 464 |
|
| 465 |
# trying to get a ticket from a service url matched by a service pattern that use |
| 466 |
# a particular attribute has username. The test user do NOT have this attribute |
| 467 |
response = client.get("/login", {'service': self.service_field_needed_fail}) |
| 468 |
# the ticket is not created and a warning is displayed to the user |
| 469 |
self.assertEqual(response.status_code, 200) |
| 470 |
self.assertTrue(b"The attribute uid is needed to use that service" in response.content) |
| 471 |
|
| 472 |
# same but with a attribute that the test user has |
| 473 |
response = client.get("/login", {'service': self.service_field_needed_success}) |
| 474 |
# the ticket us created and the user redirected to the service url |
| 475 |
self.assertEqual(response.status_code, 302) |
| 476 |
self.assertTrue( |
| 477 |
response["Location"].startswith("%s?ticket=" % self.service_field_needed_success) |
| 478 |
) |
| 479 |
|
| 480 |
@override_settings(CAS_TEST_ATTRIBUTES={'alias': []}) |
| 481 |
def test_service_user_field_evaluate_to_false(self): |
| 482 |
""" |
| 483 |
Test using a user attribute as username: |
| 484 |
case the attribute exists but evaluate to False |
| 485 |
""" |
| 486 |
# get a client that is already authenticated |
| 487 |
client = get_auth_client() |
| 488 |
# trying to get a ticket from a service url matched by a service pattern that use |
| 489 |
# a particular attribute has username. The test user have this attribute, but it is |
| 490 |
# evaluated to False (eg an empty string "" or an empty list []) |
| 491 |
response = client.get("/login", {"service": self.service_field_needed_success}) |
| 492 |
# the ticket is not created and a warning is displayed to the user |
| 493 |
self.assertEqual(response.status_code, 200) |
| 494 |
self.assertTrue(b"The attribute alias is needed to use that service" in response.content) |
| 495 |
|
| 496 |
def test_gateway(self): |
| 497 |
"""test gateway parameter""" |
| 498 |
|
| 499 |
# First with an authenticated client that fail to get a ticket for a service |
| 500 |
service = "https://restrict_user_fail.example.com" |
| 501 |
# get a client that is already authenticated |
| 502 |
client = get_auth_client() |
| 503 |
# the authenticated client fail to get a ticket for some reason |
| 504 |
response = client.get("/login", {'service': service, 'gateway': 'on'}) |
| 505 |
# as gateway is set, he is redirected to the service url without any ticket |
| 506 |
self.assertEqual(response.status_code, 302) |
| 507 |
self.assertEqual(response["Location"], service) |
| 508 |
|
| 509 |
# second for an user not yet authenticated on a valid service |
| 510 |
client = Client() |
| 511 |
# the client fail to get a ticket since he is not yep authenticated |
| 512 |
response = client.get('/login', {'service': service, 'gateway': 'on'}) |
| 513 |
# as gateway is set, he is redirected to the service url without any ticket |
| 514 |
self.assertEqual(response.status_code, 302) |
| 515 |
self.assertEqual(response["Location"], service) |
| 516 |
|
| 517 |
def test_renew(self): |
| 518 |
"""test the authentication renewal request from a service""" |
| 519 |
# use the default test service |
| 520 |
service = "https://www.example.com" |
| 521 |
# get a client that is already authenticated |
| 522 |
client = get_auth_client() |
| 523 |
# ask for a ticket for the service but aks for authentication renewal |
| 524 |
response = client.get("/login", {'service': service, 'renew': 'on'}) |
| 525 |
# we are ask to reauthenticate and tell the user why |
| 526 |
self.assertEqual(response.status_code, 200) |
| 527 |
self.assertTrue( |
| 528 |
( |
| 529 |
b"Authentication renewal required by " |
| 530 |
b"service example (https://www.example.com)" |
| 531 |
) in response.content |
| 532 |
) |
| 533 |
# get the form default parameter |
| 534 |
params = copy_form(response.context["form"]) |
| 535 |
# set valid username/password |
| 536 |
params["username"] = settings.CAS_TEST_USER |
| 537 |
params["password"] = settings.CAS_TEST_PASSWORD |
| 538 |
# the renew parameter from the form should be True |
| 539 |
self.assertEqual(params["renew"], True) |
| 540 |
# post the authentication request |
| 541 |
response = client.post("/login", params) |
| 542 |
# the request succed, a ticket is created and we are redirected to the service url |
| 543 |
self.assertEqual(response.status_code, 302) |
| 544 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 545 |
ticket = models.ServiceTicket.objects.get(value=ticket_value) |
| 546 |
# the created ticket is marked has being gottent after a renew. Futher testing about |
| 547 |
# renewing authentication is done in the validate and serviceValidate views tests |
| 548 |
self.assertEqual(ticket.renew, True) |
| 549 |
|
| 550 |
@override_settings(CAS_SHOW_SERVICE_MESSAGES=False) |
| 551 |
def test_renew_message_disabled(self): |
| 552 |
"""test the authentication renewal request from a service""" |
| 553 |
# use the default test service |
| 554 |
service = "https://www.example.com" |
| 555 |
# get a client that is already authenticated |
| 556 |
client = get_auth_client() |
| 557 |
# ask for a ticket for the service but aks for authentication renewal |
| 558 |
response = client.get("/login", {'service': service, 'renew': 'on'}) |
| 559 |
# we are ask to reauthenticate and tell the user why |
| 560 |
self.assertEqual(response.status_code, 200) |
| 561 |
self.assertFalse( |
| 562 |
( |
| 563 |
b"Authentication renewal required by " |
| 564 |
b"service example (https://www.example.com)" |
| 565 |
) in response.content |
| 566 |
) |
| 567 |
# get the form default parameter |
| 568 |
params = copy_form(response.context["form"]) |
| 569 |
# set valid username/password |
| 570 |
params["username"] = settings.CAS_TEST_USER |
| 571 |
params["password"] = settings.CAS_TEST_PASSWORD |
| 572 |
# the renew parameter from the form should be True |
| 573 |
self.assertEqual(params["renew"], True) |
| 574 |
# post the authentication request |
| 575 |
response = client.post("/login", params) |
| 576 |
# the request succed, a ticket is created and we are redirected to the service url |
| 577 |
self.assertEqual(response.status_code, 302) |
| 578 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 579 |
ticket = models.ServiceTicket.objects.get(value=ticket_value) |
| 580 |
# the created ticket is marked has being gottent after a renew. Futher testing about |
| 581 |
# renewing authentication is done in the validate and serviceValidate views tests |
| 582 |
self.assertEqual(ticket.renew, True) |
| 583 |
|
| 584 |
@override_settings(CAS_ENABLE_AJAX_AUTH=True) |
| 585 |
def test_ajax_login_required(self): |
| 586 |
""" |
| 587 |
test ajax, login required. |
| 588 |
The ajax methods allow the log a user in using javascript. |
| 589 |
For doing so, every 302 redirection a replaced by a 200 returning a json with the |
| 590 |
url to redirect to. |
| 591 |
By default, ajax login is disabled. |
| 592 |
If CAS_ENABLE_AJAX_AUTH is True, ajax login is enable and only page on the same domain |
| 593 |
as the CAS can do ajax request. To allow pages on other domains, you need to use CORS. |
| 594 |
You can use the django app corsheaders for that. Be carefull to only allow domains |
| 595 |
you completly trust as any javascript on these domaine will be able to authenticate |
| 596 |
as the user. |
| 597 |
""" |
| 598 |
# get a bare client |
| 599 |
client = Client() |
| 600 |
# fetch the login page setting up the custom header HTTP_X_AJAX to tell we wish to de |
| 601 |
# ajax requests |
| 602 |
response = client.get("/login", HTTP_X_AJAX='on') |
| 603 |
# we get a json as response telling us the user need to be authenticated |
| 604 |
self.assertEqual(response.status_code, 200) |
| 605 |
data = json.loads(response.content.decode("utf8")) |
| 606 |
self.assertEqual(data["status"], "error") |
| 607 |
self.assertEqual(data["detail"], "login required") |
| 608 |
self.assertEqual(data["url"], "/login") |
| 609 |
|
| 610 |
@override_settings(CAS_ENABLE_AJAX_AUTH=True) |
| 611 |
def test_ajax_logged_user_deleted(self): |
| 612 |
"""test ajax user logged deleted: login required""" |
| 613 |
# get a client that is already authenticated |
| 614 |
client = get_auth_client() |
| 615 |
# delete the user in the db |
| 616 |
user = models.User.objects.get( |
| 617 |
username=settings.CAS_TEST_USER, |
| 618 |
session_key=client.session.session_key |
| 619 |
) |
| 620 |
user.delete() |
| 621 |
# fetch the login page with ajax on |
| 622 |
response = client.get("/login", HTTP_X_AJAX='on') |
| 623 |
# we get a json telling us that the user need to authenticate |
| 624 |
self.assertEqual(response.status_code, 200) |
| 625 |
data = json.loads(response.content.decode("utf8")) |
| 626 |
self.assertEqual(data["status"], "error") |
| 627 |
self.assertEqual(data["detail"], "login required") |
| 628 |
self.assertEqual(data["url"], "/login") |
| 629 |
|
| 630 |
@override_settings(CAS_ENABLE_AJAX_AUTH=True) |
| 631 |
def test_ajax_logged(self): |
| 632 |
"""test ajax user is successfully logged""" |
| 633 |
# get a client that is already authenticated |
| 634 |
client = get_auth_client() |
| 635 |
# fetch the login page with ajax on |
| 636 |
response = client.get("/login", HTTP_X_AJAX='on') |
| 637 |
# we get a json telling us that the user is well authenticated |
| 638 |
self.assertEqual(response.status_code, 200) |
| 639 |
data = json.loads(response.content.decode("utf8")) |
| 640 |
self.assertEqual(data["status"], "success") |
| 641 |
self.assertEqual(data["detail"], "logged") |
| 642 |
|
| 643 |
@override_settings(CAS_ENABLE_AJAX_AUTH=True) |
| 644 |
def test_ajax_get_ticket_success(self): |
| 645 |
"""test ajax retrieve a ticket for an allowed service""" |
| 646 |
# using the default test service |
| 647 |
service = "https://www.example.com" |
| 648 |
# get a client that is already authenticated |
| 649 |
client = get_auth_client() |
| 650 |
# fetch the login page with ajax on |
| 651 |
response = client.get("/login", {'service': service}, HTTP_X_AJAX='on') |
| 652 |
# we get a json telling us that the ticket has being created |
| 653 |
# and we get the url to fetch to authenticate the user to the service |
| 654 |
# contening the ticket has GET parameter |
| 655 |
self.assertEqual(response.status_code, 200) |
| 656 |
data = json.loads(response.content.decode("utf8")) |
| 657 |
self.assertEqual(data["status"], "success") |
| 658 |
self.assertEqual(data["detail"], "auth") |
| 659 |
self.assertTrue(data["url"].startswith('%s?ticket=' % service)) |
| 660 |
|
| 661 |
def test_ajax_get_ticket_success_alt(self): |
| 662 |
""" |
| 663 |
test ajax retrieve a ticket for an allowed service. |
| 664 |
Same as above but with CAS_ENABLE_AJAX_AUTH=False |
| 665 |
""" |
| 666 |
# using the default test service |
| 667 |
service = "https://www.example.com" |
| 668 |
# get a client that is already authenticated |
| 669 |
client = get_auth_client() |
| 670 |
# fetch the login page with ajax on |
| 671 |
response = client.get("/login", {'service': service}, HTTP_X_AJAX='on') |
| 672 |
# as CAS_ENABLE_AJAX_AUTH is False the ajax request is ignored and word normally: |
| 673 |
# 302 redirect to the service url with ticket as GET parameter. javascript |
| 674 |
# cannot retieve the ticket info and try follow the redirect to an other domain and fail |
| 675 |
# silently |
| 676 |
self.assertEqual(response.status_code, 302) |
| 677 |
|
| 678 |
@override_settings(CAS_ENABLE_AJAX_AUTH=True) |
| 679 |
def test_ajax_get_ticket_fail(self): |
| 680 |
"""test ajax retrieve a ticket for a denied service""" |
| 681 |
# using a denied service url |
| 682 |
service = "https://www.example.org" |
| 683 |
# get a client that is already authenticated |
| 684 |
client = get_auth_client() |
| 685 |
# fetch the login page with ajax on |
| 686 |
response = client.get("/login", {'service': service}, HTTP_X_AJAX='on') |
| 687 |
# we get a json telling us that the service is not allowed |
| 688 |
self.assertEqual(response.status_code, 200) |
| 689 |
data = json.loads(response.content.decode("utf8")) |
| 690 |
self.assertEqual(data["status"], "error") |
| 691 |
self.assertEqual(data["detail"], "auth") |
| 692 |
self.assertEqual(data["messages"][0]["level"], "error") |
| 693 |
self.assertEqual( |
| 694 |
data["messages"][0]["message"], |
| 695 |
"Service https://www.example.org not allowed." |
| 696 |
) |
| 697 |
|
| 698 |
@override_settings(CAS_ENABLE_AJAX_AUTH=True) |
| 699 |
def test_ajax_get_ticket_warn(self): |
| 700 |
"""test get a ticket but user asked to be warned""" |
| 701 |
# using the default test service |
| 702 |
service = "https://www.example.com" |
| 703 |
# get a client that is already authenticated wth warn on |
| 704 |
client = get_auth_client(warn="on") |
| 705 |
# fetch the login page with ajax on |
| 706 |
response = client.get("/login", {'service': service}, HTTP_X_AJAX='on') |
| 707 |
# we get a json telling us that we cannot get a ticket transparently and that the |
| 708 |
# user has asked to be warned |
| 709 |
self.assertEqual(response.status_code, 200) |
| 710 |
data = json.loads(response.content.decode("utf8")) |
| 711 |
self.assertEqual(data["status"], "error") |
| 712 |
self.assertEqual(data["detail"], "confirmation needed") |
| 713 |
|
| 714 |
|
| 715 |
@override_settings(CAS_AUTH_CLASS='cas_server.auth.TestAuthUser') |
| 716 |
class LogoutTestCase(TestCase): |
| 717 |
"""test fot the logout view""" |
| 718 |
def setUp(self): |
| 719 |
"""Prepare the test context""" |
| 720 |
# for testing SingleLogOut we need to use a service on localhost were we lanch |
| 721 |
# a simple one request http server |
| 722 |
self.service = 'http://127.0.0.1:45678' |
| 723 |
self.service_pattern = models.ServicePattern.objects.create( |
| 724 |
name="localhost", |
| 725 |
pattern=r"^https?://127\.0\.0\.1(:[0-9]+)?(/.*)?$", |
| 726 |
single_log_out=True |
| 727 |
) |
| 728 |
# return all user attributes |
| 729 |
models.ReplaceAttributName.objects.create(name="*", service_pattern=self.service_pattern) |
| 730 |
|
| 731 |
def test_logout(self): |
| 732 |
"""logout is idempotent""" |
| 733 |
# get a bare client |
| 734 |
client = Client() |
| 735 |
|
| 736 |
# call logout |
| 737 |
client.get("/logout") |
| 738 |
|
| 739 |
# we are still not logged |
| 740 |
self.assertFalse(client.session.get("username")) |
| 741 |
self.assertFalse(client.session.get("authenticated")) |
| 742 |
|
| 743 |
def test_logout_view(self): |
| 744 |
"""test simple logout, logout only an user from one and only one sessions""" |
| 745 |
# get two authenticated client with the same test user (but two different sessions) |
| 746 |
client = get_auth_client() |
| 747 |
client2 = get_auth_client() |
| 748 |
|
| 749 |
# fetch login, the first client is well authenticated |
| 750 |
response = client.get("/login") |
| 751 |
self.assertEqual(response.status_code, 200) |
| 752 |
self.assertTrue( |
| 753 |
( |
| 754 |
b"You have successfully logged into " |
| 755 |
b"the Central Authentication Service" |
| 756 |
) in response.content |
| 757 |
) |
| 758 |
# and session variable are well |
| 759 |
self.assertTrue(client.session["username"] == settings.CAS_TEST_USER) |
| 760 |
self.assertTrue(client.session["authenticated"] is True) |
| 761 |
|
| 762 |
# call logout with the first client |
| 763 |
response = client.get("/logout") |
| 764 |
# the client is logged out |
| 765 |
self.assertEqual(response.status_code, 200) |
| 766 |
self.assertTrue( |
| 767 |
( |
| 768 |
b"You have successfully logged out from " |
| 769 |
b"the Central Authentication Service" |
| 770 |
) in response.content |
| 771 |
) |
| 772 |
# and session variable a well cleaned |
| 773 |
self.assertFalse(client.session.get("username")) |
| 774 |
self.assertFalse(client.session.get("authenticated")) |
| 775 |
# client2 is still logged |
| 776 |
self.assertTrue(client2.session["username"] == settings.CAS_TEST_USER) |
| 777 |
self.assertTrue(client2.session["authenticated"] is True) |
| 778 |
|
| 779 |
response = client.get("/login") |
| 780 |
# fetch login, the second client is well authenticated |
| 781 |
self.assertEqual(response.status_code, 200) |
| 782 |
self.assertFalse( |
| 783 |
( |
| 784 |
b"You have successfully logged into " |
| 785 |
b"the Central Authentication Service" |
| 786 |
) in response.content |
| 787 |
) |
| 788 |
|
| 789 |
def test_logout_from_all_session(self): |
| 790 |
"""test logout from all my session""" |
| 791 |
# get two authenticated client with the same test user (but two different sessions) |
| 792 |
client = get_auth_client() |
| 793 |
client2 = get_auth_client() |
| 794 |
|
| 795 |
# call logout with the first client and ask to be logged out from all of this user sessions |
| 796 |
client.get("/logout?all=1") |
| 797 |
|
| 798 |
# both client are logged out |
| 799 |
self.assertFalse(client.session.get("username")) |
| 800 |
self.assertFalse(client.session.get("authenticated")) |
| 801 |
self.assertFalse(client2.session.get("username")) |
| 802 |
self.assertFalse(client2.session.get("authenticated")) |
| 803 |
|
| 804 |
def assert_redirect_to_service(self, client, response): |
| 805 |
"""assert logout redirect to parameter""" |
| 806 |
# assert a redirection with a service |
| 807 |
self.assertEqual(response.status_code, 302) |
| 808 |
self.assertTrue(response.has_header("Location")) |
| 809 |
self.assertEqual(response["Location"], "https://www.example.com") |
| 810 |
|
| 811 |
response = client.get("/login") |
| 812 |
self.assertEqual(response.status_code, 200) |
| 813 |
# assert we are not longer logged in |
| 814 |
self.assertFalse( |
| 815 |
( |
| 816 |
b"You have successfully logged into " |
| 817 |
b"the Central Authentication Service" |
| 818 |
) in response.content |
| 819 |
) |
| 820 |
|
| 821 |
def test_logout_view_url(self): |
| 822 |
"""test logout redirect to url parameter""" |
| 823 |
# get a client that is authenticated |
| 824 |
client = get_auth_client() |
| 825 |
|
| 826 |
# logout with an url paramer |
| 827 |
response = client.get('/logout?url=https://www.example.com') |
| 828 |
# we are redirected to the addresse of the url parameter |
| 829 |
self.assert_redirect_to_service(client, response) |
| 830 |
|
| 831 |
def test_logout_view_service(self): |
| 832 |
"""test logout redirect to service parameter""" |
| 833 |
# get a client that is authenticated |
| 834 |
client = get_auth_client() |
| 835 |
|
| 836 |
# logout with a service parameter |
| 837 |
response = client.get('/logout?service=https://www.example.com') |
| 838 |
# we are redirected to the addresse of the service parameter |
| 839 |
self.assert_redirect_to_service(client, response) |
| 840 |
|
| 841 |
def test_logout_slo(self): |
| 842 |
"""test logout from a service with SLO support""" |
| 843 |
parameters = [] |
| 844 |
|
| 845 |
# test normal SLO |
| 846 |
# setup a simple one request http server |
| 847 |
(httpd, host, port) = HttpParamsHandler.run()[0:3] |
| 848 |
# build a service url depending on which port the http server has binded |
| 849 |
service = "http://%s:%s" % (host, port) |
| 850 |
# get a ticket requested by client and being validated by the service |
| 851 |
(client, ticket) = get_validated_ticket(service)[:2] |
| 852 |
# the client logout triggering the send of the SLO requests |
| 853 |
client.get('/logout') |
| 854 |
# we store the POST parameters send for this ticket for furthur analisys |
| 855 |
parameters.append((httpd.PARAMS, ticket)) |
| 856 |
|
| 857 |
# text SLO with a single_log_out_callback |
| 858 |
# setup a simple one request http server |
| 859 |
(httpd, host, port) = HttpParamsHandler.run()[0:3] |
| 860 |
# set the default test service pattern to use the http server port for SLO requests. |
| 861 |
# in fact, this single_log_out_callback parametter is usefull to implement SLO |
| 862 |
# for non http service like imap or ftp |
| 863 |
self.service_pattern.single_log_out_callback = "http://%s:%s" % (host, port) |
| 864 |
self.service_pattern.save() |
| 865 |
# get a ticket requested by client and being validated by the service |
| 866 |
(client, ticket) = get_validated_ticket(self.service)[:2] |
| 867 |
# the client logout triggering the send of the SLO requests |
| 868 |
client.get('/logout') |
| 869 |
# we store the POST parameters send for this ticket for furthur analisys |
| 870 |
parameters.append((httpd.PARAMS, ticket)) |
| 871 |
|
| 872 |
# for earch POST parameters and corresponding ticket |
| 873 |
for (params, ticket) in parameters: |
| 874 |
# there is a POST parameter 'logoutRequest' |
| 875 |
self.assertTrue(b'logoutRequest' in params and params[b'logoutRequest']) |
| 876 |
|
| 877 |
# it is a valid xml |
| 878 |
root = etree.fromstring(params[b'logoutRequest'][0]) |
| 879 |
# contening a <samlp:LogoutRequest> tag |
| 880 |
self.assertTrue( |
| 881 |
root.xpath( |
| 882 |
"//samlp:LogoutRequest", |
| 883 |
namespaces={"samlp": "urn:oasis:names:tc:SAML:2.0:protocol"} |
| 884 |
) |
| 885 |
) |
| 886 |
# with a tag <samlp:SessionIndex> enclosing the value of the ticket |
| 887 |
session_index = root.xpath( |
| 888 |
"//samlp:SessionIndex", |
| 889 |
namespaces={"samlp": "urn:oasis:names:tc:SAML:2.0:protocol"} |
| 890 |
) |
| 891 |
self.assertEqual(len(session_index), 1) |
| 892 |
self.assertEqual(session_index[0].text, ticket.value) |
| 893 |
|
| 894 |
# SLO error are displayed on logout page |
| 895 |
(client, ticket) = get_validated_ticket(self.service)[:2] |
| 896 |
# the client logout triggering the send of the SLO requests but |
| 897 |
# not http server are listening |
| 898 |
response = client.get('/logout') |
| 899 |
self.assertTrue(b"Error during service logout" in response.content) |
| 900 |
|
| 901 |
@override_settings(CAS_ENABLE_AJAX_AUTH=True) |
| 902 |
def test_ajax_logout(self): |
| 903 |
""" |
| 904 |
test ajax logout. These methods are here, but I do not really see an use case for |
| 905 |
javascript logout |
| 906 |
""" |
| 907 |
# get a client that is authenticated |
| 908 |
client = get_auth_client() |
| 909 |
|
| 910 |
# fetch the logout page with ajax on |
| 911 |
response = client.get('/logout', HTTP_X_AJAX='on') |
| 912 |
# we get a json telling us the user is well logged out |
| 913 |
self.assertEqual(response.status_code, 200) |
| 914 |
data = json.loads(response.content.decode("utf8")) |
| 915 |
self.assertEqual(data["status"], "success") |
| 916 |
self.assertEqual(data["detail"], "logout") |
| 917 |
self.assertEqual(data['session_nb'], 1) |
| 918 |
|
| 919 |
@override_settings(CAS_ENABLE_AJAX_AUTH=True) |
| 920 |
def test_ajax_logout_all_session(self): |
| 921 |
"""test ajax logout from a random number a sessions""" |
| 922 |
# fire a random int in [2, 10[ |
| 923 |
nb_client = random.randint(2, 10) |
| 924 |
# get this much of logged clients all for the test user |
| 925 |
clients = [get_auth_client() for i in range(nb_client)] |
| 926 |
# fetch the logout page with ajax on, requesting to logout from all sessions |
| 927 |
response = clients[0].get('/logout?all=1', HTTP_X_AJAX='on') |
| 928 |
# we get a json telling us the user is well logged out and the number of session |
| 929 |
# the user has being logged out |
| 930 |
self.assertEqual(response.status_code, 200) |
| 931 |
data = json.loads(response.content.decode("utf8")) |
| 932 |
self.assertEqual(data["status"], "success") |
| 933 |
self.assertEqual(data["detail"], "logout") |
| 934 |
self.assertEqual(data['session_nb'], nb_client) |
| 935 |
|
| 936 |
@override_settings(CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT=True) |
| 937 |
def test_redirect_after_logout(self): |
| 938 |
"""Test redirect to login after logout parameter""" |
| 939 |
# get a client that is authenticated |
| 940 |
client = get_auth_client() |
| 941 |
|
| 942 |
# fetch the logout page |
| 943 |
response = client.get('/logout') |
| 944 |
# as CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT is True, we are redirected to the login page |
| 945 |
self.assertEqual(response.status_code, 302) |
| 946 |
if django.VERSION < (1, 9): # pragma: no cover coverage is computed with dango 1.9 |
| 947 |
self.assertEqual(response["Location"], "http://testserver/login") |
| 948 |
else: |
| 949 |
self.assertEqual(response["Location"], "/login") |
| 950 |
self.assertFalse(client.session.get("username")) |
| 951 |
self.assertFalse(client.session.get("authenticated")) |
| 952 |
|
| 953 |
@override_settings(CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT=True) |
| 954 |
def test_redirect_after_logout_to_service(self): |
| 955 |
"""test prevalence of redirect url/service parameter over redirect to login after logout""" |
| 956 |
# get a client that is authenticated |
| 957 |
client = get_auth_client() |
| 958 |
|
| 959 |
# fetch the logout page with an url parameter |
| 960 |
response = client.get('/logout?url=https://www.example.com') |
| 961 |
# we are redirected to the url parameter and not to the login page |
| 962 |
self.assert_redirect_to_service(client, response) |
| 963 |
|
| 964 |
# fetch the logout page with an service parameter |
| 965 |
response = client.get('/logout?service=https://www.example.com') |
| 966 |
# we are redirected to the service parameter and not to the login page |
| 967 |
self.assert_redirect_to_service(client, response) |
| 968 |
|
| 969 |
@override_settings(CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT=True, CAS_ENABLE_AJAX_AUTH=True) |
| 970 |
def test_ajax_redirect_after_logout(self): |
| 971 |
"""Test ajax redirect to login after logout parameter""" |
| 972 |
# get a client that is authenticated |
| 973 |
client = get_auth_client() |
| 974 |
|
| 975 |
# fetch the logout page with ajax on |
| 976 |
response = client.get('/logout', HTTP_X_AJAX='on') |
| 977 |
# we get a json telling us the user is well logged out. And url key is added to aks for |
| 978 |
# redirection to the login page |
| 979 |
self.assertEqual(response.status_code, 200) |
| 980 |
data = json.loads(response.content.decode("utf8")) |
| 981 |
self.assertEqual(data["status"], "success") |
| 982 |
self.assertEqual(data["detail"], "logout") |
| 983 |
self.assertEqual(data['session_nb'], 1) |
| 984 |
self.assertEqual(data['url'], '/login') |
| 985 |
|
| 986 |
|
| 987 |
@override_settings(CAS_AUTH_CLASS='cas_server.auth.TestAuthUser') |
| 988 |
class AuthTestCase(TestCase): |
| 989 |
""" |
| 990 |
Test for the auth view, used for external services |
| 991 |
to validate (user, pass, service) tuples. |
| 992 |
""" |
| 993 |
def setUp(self): |
| 994 |
"""preparing test context""" |
| 995 |
# setting up a default test service url and pattern |
| 996 |
self.service = 'https://www.example.com' |
| 997 |
models.ServicePattern.objects.create( |
| 998 |
name="example", |
| 999 |
pattern=r"^https://www\.example\.com(/.*)?$" |
| 1000 |
) |
| 1001 |
|
| 1002 |
@override_settings(CAS_AUTH_SHARED_SECRET='test') |
| 1003 |
def test_auth_view_goodpass(self): |
| 1004 |
"""successful request are awsered by yes""" |
| 1005 |
# get a bare client |
| 1006 |
client = Client() |
| 1007 |
# post the the auth view a valid (username, password, service) and the shared secret |
| 1008 |
# to test the user again the service, a user is created in the database for the |
| 1009 |
# current session and is then deleted as the user is not authenticated |
| 1010 |
response = client.post( |
| 1011 |
'/auth', |
| 1012 |
{ |
| 1013 |
'username': settings.CAS_TEST_USER, |
| 1014 |
'password': settings.CAS_TEST_PASSWORD, |
| 1015 |
'service': self.service, |
| 1016 |
'secret': 'test' |
| 1017 |
} |
| 1018 |
) |
| 1019 |
# as (username, password, service) and the hared secret are valid, we get yes as a response |
| 1020 |
self.assertEqual(response.status_code, 200) |
| 1021 |
self.assertEqual(response.content, b'yes\n') |
| 1022 |
|
| 1023 |
@override_settings(CAS_AUTH_SHARED_SECRET='test') |
| 1024 |
def test_auth_view_goodpass_logged(self): |
| 1025 |
"""successful request are awsered by yes, using a logged sessions""" |
| 1026 |
# same as above |
| 1027 |
client = get_auth_client() |
| 1028 |
# to test the user again the service, a user is fetch in the database for the |
| 1029 |
# current session and is NOT deleted as the user is currently logged. |
| 1030 |
# Deleting the user from the database would cause the user to be logged out as |
| 1031 |
# showed in the login tests |
| 1032 |
response = client.post( |
| 1033 |
'/auth', |
| 1034 |
{ |
| 1035 |
'username': settings.CAS_TEST_USER, |
| 1036 |
'password': settings.CAS_TEST_PASSWORD, |
| 1037 |
'service': self.service, |
| 1038 |
'secret': 'test' |
| 1039 |
} |
| 1040 |
) |
| 1041 |
# as (username, password, service) and the hared secret are valid, we get yes as a response |
| 1042 |
self.assertEqual(response.status_code, 200) |
| 1043 |
self.assertEqual(response.content, b'yes\n') |
| 1044 |
|
| 1045 |
@override_settings(CAS_AUTH_SHARED_SECRET='test') |
| 1046 |
def test_auth_view_badpass(self): |
| 1047 |
""" bag user password => no""" |
| 1048 |
client = Client() |
| 1049 |
response = client.post( |
| 1050 |
'/auth', |
| 1051 |
{ |
| 1052 |
'username': settings.CAS_TEST_USER, |
| 1053 |
'password': 'badpass', |
| 1054 |
'service': self.service, |
| 1055 |
'secret': 'test' |
| 1056 |
} |
| 1057 |
) |
| 1058 |
self.assertEqual(response.status_code, 200) |
| 1059 |
self.assertEqual(response.content, b'no\n') |
| 1060 |
|
| 1061 |
@override_settings(CAS_AUTH_SHARED_SECRET='test') |
| 1062 |
def test_auth_view_badservice(self): |
| 1063 |
"""bad service => no""" |
| 1064 |
client = Client() |
| 1065 |
response = client.post( |
| 1066 |
'/auth', |
| 1067 |
{ |
| 1068 |
'username': settings.CAS_TEST_USER, |
| 1069 |
'password': settings.CAS_TEST_PASSWORD, |
| 1070 |
'service': 'https://www.example.org', |
| 1071 |
'secret': 'test' |
| 1072 |
} |
| 1073 |
) |
| 1074 |
self.assertEqual(response.status_code, 200) |
| 1075 |
self.assertEqual(response.content, b'no\n') |
| 1076 |
|
| 1077 |
@override_settings(CAS_AUTH_SHARED_SECRET='test') |
| 1078 |
def test_auth_view_badsecret(self): |
| 1079 |
"""bad api key => no""" |
| 1080 |
client = Client() |
| 1081 |
response = client.post( |
| 1082 |
'/auth', |
| 1083 |
{ |
| 1084 |
'username': settings.CAS_TEST_USER, |
| 1085 |
'password': settings.CAS_TEST_PASSWORD, |
| 1086 |
'service': self.service, |
| 1087 |
'secret': 'badsecret' |
| 1088 |
} |
| 1089 |
) |
| 1090 |
self.assertEqual(response.status_code, 200) |
| 1091 |
self.assertEqual(response.content, b'no\n') |
| 1092 |
|
| 1093 |
def test_auth_view_badsettings(self): |
| 1094 |
"""api not set => error""" |
| 1095 |
client = Client() |
| 1096 |
response = client.post( |
| 1097 |
'/auth', |
| 1098 |
{ |
| 1099 |
'username': settings.CAS_TEST_USER, |
| 1100 |
'password': settings.CAS_TEST_PASSWORD, |
| 1101 |
'service': self.service, |
| 1102 |
'secret': 'test' |
| 1103 |
} |
| 1104 |
) |
| 1105 |
self.assertEqual(response.status_code, 200) |
| 1106 |
self.assertEqual(response.content, b"no\nplease set CAS_AUTH_SHARED_SECRET") |
| 1107 |
|
| 1108 |
@override_settings(CAS_AUTH_SHARED_SECRET='test') |
| 1109 |
def test_auth_view_missing_parameter(self): |
| 1110 |
"""missing parameter in request => no""" |
| 1111 |
client = Client() |
| 1112 |
params = { |
| 1113 |
'username': settings.CAS_TEST_USER, |
| 1114 |
'password': settings.CAS_TEST_PASSWORD, |
| 1115 |
'service': self.service, |
| 1116 |
'secret': 'test' |
| 1117 |
} |
| 1118 |
for key in ['username', 'password', 'service']: |
| 1119 |
send_params = params.copy() |
| 1120 |
del send_params[key] |
| 1121 |
response = client.post('/auth', send_params) |
| 1122 |
self.assertEqual(response.status_code, 200) |
| 1123 |
self.assertEqual(response.content, b'no\n') |
| 1124 |
|
| 1125 |
|
| 1126 |
@override_settings(CAS_AUTH_CLASS='cas_server.auth.TestAuthUser') |
| 1127 |
class ValidateTestCase(TestCase): |
| 1128 |
"""tests for the validate view""" |
| 1129 |
def setUp(self): |
| 1130 |
"""preparing test context""" |
| 1131 |
# setting up a default test service url and pattern |
| 1132 |
self.service = 'https://www.example.com' |
| 1133 |
self.service_pattern = models.ServicePattern.objects.create( |
| 1134 |
name="example", |
| 1135 |
pattern=r"^https://www\.example\.com(/.*)?$" |
| 1136 |
) |
| 1137 |
models.ReplaceAttributName.objects.create(name="*", service_pattern=self.service_pattern) |
| 1138 |
# setting up a test service and pattern using a multi valued user attribut as username |
| 1139 |
# the first value of the list should be used as username |
| 1140 |
self.service_user_field = "https://user_field.example.com" |
| 1141 |
self.service_pattern_user_field = models.ServicePattern.objects.create( |
| 1142 |
name="user field", |
| 1143 |
pattern=r"^https://user_field\.example\.com(/.*)?$", |
| 1144 |
user_field="alias" |
| 1145 |
) |
| 1146 |
# setting up a test service and pattern using a single valued user attribut as username |
| 1147 |
self.service_user_field_alt = "https://user_field_alt.example.com" |
| 1148 |
self.service_pattern_user_field_alt = models.ServicePattern.objects.create( |
| 1149 |
name="user field alt", |
| 1150 |
pattern=r"^https://user_field_alt\.example\.com(/.*)?$", |
| 1151 |
user_field="nom" |
| 1152 |
) |
| 1153 |
|
| 1154 |
def test_validate_view_ok(self): |
| 1155 |
"""test for a valid (ticket, service)""" |
| 1156 |
# get a ticket waiting to be validated for self.service |
| 1157 |
ticket = get_user_ticket_request(self.service)[1] |
| 1158 |
|
| 1159 |
# get a bare client |
| 1160 |
client = Client() |
| 1161 |
# calling the validate view with this ticket value and service |
| 1162 |
response = client.get('/validate', {'ticket': ticket.value, 'service': self.service}) |
| 1163 |
# get yes as a response and the test user username |
| 1164 |
self.assertEqual(response.status_code, 200) |
| 1165 |
self.assertEqual(response.content, b'yes\ntest\n') |
| 1166 |
|
| 1167 |
def test_validate_service_renew(self): |
| 1168 |
"""test with a valid (ticket, service) asking for auth renewal""" |
| 1169 |
# case 1 client is renewing and service ask for renew |
| 1170 |
response = get_auth_client(renew="True", service=self.service)[1] |
| 1171 |
self.assertEqual(response.status_code, 302) |
| 1172 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 1173 |
# get a bare client |
| 1174 |
client = Client() |
| 1175 |
# requesting validation with a good (ticket, service) |
| 1176 |
response = client.get( |
| 1177 |
'/validate', |
| 1178 |
{'ticket': ticket_value, 'service': self.service, 'renew': 'True'} |
| 1179 |
) |
| 1180 |
# the validation should succes with username settings.CAS_TEST_USER and transmit |
| 1181 |
self.assertEqual(response.status_code, 200) |
| 1182 |
self.assertEqual(response.content, b'yes\ntest\n') |
| 1183 |
|
| 1184 |
# cas2 client is renewing and service do not ask for renew |
| 1185 |
(client2, response) = get_auth_client(renew="True", service=self.service) |
| 1186 |
self.assertEqual(response.status_code, 302) |
| 1187 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 1188 |
# get a bare client |
| 1189 |
client = Client() |
| 1190 |
# requesting validation with a good (ticket, service) |
| 1191 |
response = client.get( |
| 1192 |
'/validate', |
| 1193 |
{'ticket': ticket_value, 'service': self.service} |
| 1194 |
) |
| 1195 |
# the validation should succes with username settings.CAS_TEST_USER and transmit |
| 1196 |
self.assertEqual(response.status_code, 200) |
| 1197 |
self.assertEqual(response.content, b'yes\ntest\n') |
| 1198 |
|
| 1199 |
# case 3, client is not renewing and service ask for renew (client is authenticated) |
| 1200 |
response = client2.get("/login", {"service": self.service}) |
| 1201 |
self.assertEqual(response.status_code, 302) |
| 1202 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 1203 |
client = Client() |
| 1204 |
# requesting validation with a good (ticket, service) |
| 1205 |
response = client.get( |
| 1206 |
'/validate', |
| 1207 |
{'ticket': ticket_value, 'service': self.service, 'renew': 'True'} |
| 1208 |
) |
| 1209 |
# the validation should fail |
| 1210 |
self.assertEqual(response.status_code, 200) |
| 1211 |
self.assertEqual(response.content, b'no\n') |
| 1212 |
|
| 1213 |
def test_validate_view_badservice(self): |
| 1214 |
"""test for a valid ticket but bad service""" |
| 1215 |
ticket = get_user_ticket_request(self.service)[1] |
| 1216 |
|
| 1217 |
client = Client() |
| 1218 |
# calling the validate view with this ticket value and another service |
| 1219 |
response = client.get( |
| 1220 |
'/validate', |
| 1221 |
{'ticket': ticket.value, 'service': "https://www.example.org"} |
| 1222 |
) |
| 1223 |
# the ticket service and validation service do not match, validation should fail |
| 1224 |
self.assertEqual(response.status_code, 200) |
| 1225 |
self.assertEqual(response.content, b'no\n') |
| 1226 |
|
| 1227 |
def test_validate_view_badticket(self): |
| 1228 |
"""test for a bad ticket but valid service""" |
| 1229 |
get_user_ticket_request(self.service) |
| 1230 |
|
| 1231 |
client = Client() |
| 1232 |
# calling the validate view with another ticket value and this service |
| 1233 |
response = client.get( |
| 1234 |
'/validate', |
| 1235 |
{'ticket': "%s-RANDOM" % settings.CAS_SERVICE_TICKET_PREFIX, 'service': self.service} |
| 1236 |
) |
| 1237 |
# as the ticket is bad, validation should fail |
| 1238 |
self.assertEqual(response.status_code, 200) |
| 1239 |
self.assertEqual(response.content, b'no\n') |
| 1240 |
|
| 1241 |
def test_validate_user_field_ok(self): |
| 1242 |
""" |
| 1243 |
test with a good user_field. A bad user_field (that evaluate to False) |
| 1244 |
wont happed cause it is filtered in the login view |
| 1245 |
""" |
| 1246 |
for (service, username) in [ |
| 1247 |
(self.service_user_field, b"demo1"), |
| 1248 |
(self.service_user_field_alt, b"Nymous") |
| 1249 |
]: |
| 1250 |
ticket = get_user_ticket_request(service)[1] |
| 1251 |
client = Client() |
| 1252 |
response = client.get( |
| 1253 |
'/validate', |
| 1254 |
{'ticket': ticket.value, 'service': service} |
| 1255 |
) |
| 1256 |
self.assertEqual(response.status_code, 200) |
| 1257 |
# the user attribute is well used as username |
| 1258 |
self.assertEqual(response.content, b'yes\n' + username + b'\n') |
| 1259 |
|
| 1260 |
def test_validate_missing_parameter(self): |
| 1261 |
"""test with a missing GET parameter among [service, ticket]""" |
| 1262 |
ticket = get_user_ticket_request(self.service)[1] |
| 1263 |
|
| 1264 |
client = Client() |
| 1265 |
params = {'ticket': ticket.value, 'service': self.service} |
| 1266 |
for key in ['ticket', 'service']: |
| 1267 |
send_params = params.copy() |
| 1268 |
del send_params[key] |
| 1269 |
response = client.get('/validate', send_params) |
| 1270 |
# if the GET request is missing the ticket or |
| 1271 |
# service GET parameter, validation should fail |
| 1272 |
self.assertEqual(response.status_code, 200) |
| 1273 |
self.assertEqual(response.content, b'no\n') |
| 1274 |
|
| 1275 |
|
| 1276 |
@override_settings(CAS_AUTH_CLASS='cas_server.auth.TestAuthUser') |
| 1277 |
class ValidateServiceTestCase(TestCase, XmlContent): |
| 1278 |
"""tests for the serviceValidate view""" |
| 1279 |
def setUp(self): |
| 1280 |
"""preparing test context""" |
| 1281 |
# for testing SingleLogOut and Proxy GrantingTicket transmission |
| 1282 |
# we need to use a service on localhost were we launch |
| 1283 |
# a simple one request http server |
| 1284 |
self.service = 'http://127.0.0.1:45678' |
| 1285 |
self.service_pattern = models.ServicePattern.objects.create( |
| 1286 |
name="localhost", |
| 1287 |
pattern=r"^https?://127\.0\.0\.1(:[0-9]+)?(/.*)?$", |
| 1288 |
# allow to request PGT by the service |
| 1289 |
proxy_callback=True, |
| 1290 |
# allow to request PT for the service |
| 1291 |
proxy=True |
| 1292 |
) |
| 1293 |
# tell the service pattern to transmit all the user attributes (* is a joker) |
| 1294 |
models.ReplaceAttributName.objects.create(name="*", service_pattern=self.service_pattern) |
| 1295 |
|
| 1296 |
# test service pattern using the attribute alias as username |
| 1297 |
self.service_user_field = "https://user_field.example.com" |
| 1298 |
self.service_pattern_user_field = models.ServicePattern.objects.create( |
| 1299 |
name="user field", |
| 1300 |
pattern=r"^https://user_field\.example\.com(/.*)?$", |
| 1301 |
user_field="alias" |
| 1302 |
) |
| 1303 |
# test service pattern using the attribute nom as username |
| 1304 |
self.service_user_field_alt = "https://user_field_alt.example.com" |
| 1305 |
self.service_pattern_user_field_alt = models.ServicePattern.objects.create( |
| 1306 |
name="user field alt", |
| 1307 |
pattern=r"^https://user_field_alt\.example\.com(/.*)?$", |
| 1308 |
user_field="nom" |
| 1309 |
) |
| 1310 |
|
| 1311 |
# test service pattern only transmiting one single attributes |
| 1312 |
self.service_one_attribute = "https://one_attribute.example.com" |
| 1313 |
self.service_pattern_one_attribute = models.ServicePattern.objects.create( |
| 1314 |
name="one_attribute", |
| 1315 |
pattern=r"^https://one_attribute\.example\.com(/.*)?$" |
| 1316 |
) |
| 1317 |
models.ReplaceAttributName.objects.create( |
| 1318 |
name="nom", |
| 1319 |
service_pattern=self.service_pattern_one_attribute |
| 1320 |
) |
| 1321 |
|
| 1322 |
# test service pattern testing attribute name and value replacement |
| 1323 |
self.service_replace_attribute_list = "https://replace_attribute_list.example.com" |
| 1324 |
self.service_pattern_replace_attribute_list = models.ServicePattern.objects.create( |
| 1325 |
name="replace_attribute_list", |
| 1326 |
pattern=r"^https://replace_attribute_list\.example\.com(/.*)?$", |
| 1327 |
) |
| 1328 |
models.ReplaceAttributValue.objects.create( |
| 1329 |
attribut="alias", |
| 1330 |
pattern="^demo", |
| 1331 |
replace="truc", |
| 1332 |
service_pattern=self.service_pattern_replace_attribute_list |
| 1333 |
) |
| 1334 |
models.ReplaceAttributName.objects.create( |
| 1335 |
name="alias", |
| 1336 |
replace="ALIAS", |
| 1337 |
service_pattern=self.service_pattern_replace_attribute_list |
| 1338 |
) |
| 1339 |
self.service_replace_attribute = "https://replace_attribute.example.com" |
| 1340 |
self.service_pattern_replace_attribute = models.ServicePattern.objects.create( |
| 1341 |
name="replace_attribute", |
| 1342 |
pattern=r"^https://replace_attribute\.example\.com(/.*)?$", |
| 1343 |
) |
| 1344 |
models.ReplaceAttributValue.objects.create( |
| 1345 |
attribut="nom", |
| 1346 |
pattern="N", |
| 1347 |
replace="P", |
| 1348 |
service_pattern=self.service_pattern_replace_attribute |
| 1349 |
) |
| 1350 |
models.ReplaceAttributName.objects.create( |
| 1351 |
name="nom", |
| 1352 |
replace="NOM", |
| 1353 |
service_pattern=self.service_pattern_replace_attribute |
| 1354 |
) |
| 1355 |
|
| 1356 |
def test_validate_service_view_ok(self): |
| 1357 |
"""test with a valid (ticket, service), the username and all attributes are transmited""" |
| 1358 |
# get a ticket from an authenticated user waiting for validation |
| 1359 |
ticket = get_user_ticket_request(self.service)[1] |
| 1360 |
|
| 1361 |
# get a bare client |
| 1362 |
client = Client() |
| 1363 |
# requesting validation with a good (ticket, service) |
| 1364 |
response = client.get('/serviceValidate', {'ticket': ticket.value, 'service': self.service}) |
| 1365 |
# the validation should succes with username settings.CAS_TEST_USER and transmit |
| 1366 |
# the attributes settings.CAS_TEST_ATTRIBUTES |
| 1367 |
self.assert_success(response, settings.CAS_TEST_USER, settings.CAS_TEST_ATTRIBUTES) |
| 1368 |
|
| 1369 |
def test_validate_proxy(self): |
| 1370 |
"""test ProxyTicket validation on /proxyValidate and /serviceValidate""" |
| 1371 |
ticket = get_proxy_ticket(self.service) |
| 1372 |
client = Client() |
| 1373 |
# requesting validation with a good (ticket, service) |
| 1374 |
response = client.get('/proxyValidate', {'ticket': ticket.value, 'service': self.service}) |
| 1375 |
# and it should succeed |
| 1376 |
self.assert_success(response, settings.CAS_TEST_USER, settings.CAS_TEST_ATTRIBUTES) |
| 1377 |
|
| 1378 |
ticket = get_proxy_ticket(self.service) |
| 1379 |
client = Client() |
| 1380 |
# requesting validation with a good (ticket, service) |
| 1381 |
response = client.get('/serviceValidate', {'ticket': ticket.value, 'service': self.service}) |
| 1382 |
# and it should succeed |
| 1383 |
self.assert_error( |
| 1384 |
response, |
| 1385 |
"INVALID_TICKET", |
| 1386 |
ticket.value |
| 1387 |
) |
| 1388 |
|
| 1389 |
def test_validate_service_renew(self): |
| 1390 |
"""test with a valid (ticket, service) asking for auth renewal""" |
| 1391 |
# case 1 client is renewing and service ask for renew |
| 1392 |
response = get_auth_client(renew="True", service=self.service)[1] |
| 1393 |
self.assertEqual(response.status_code, 302) |
| 1394 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 1395 |
# get a bare client |
| 1396 |
client = Client() |
| 1397 |
# requesting validation with a good (ticket, service) |
| 1398 |
response = client.get( |
| 1399 |
'/serviceValidate', |
| 1400 |
{'ticket': ticket_value, 'service': self.service, 'renew': 'True'} |
| 1401 |
) |
| 1402 |
# the validation should succes with username settings.CAS_TEST_USER and transmit |
| 1403 |
# the attributes settings.CAS_TEST_ATTRIBUTES |
| 1404 |
self.assert_success(response, settings.CAS_TEST_USER, settings.CAS_TEST_ATTRIBUTES) |
| 1405 |
|
| 1406 |
# cas2 client is renewing and service do not ask for renew |
| 1407 |
(client2, response) = get_auth_client(renew="True", service=self.service) |
| 1408 |
self.assertEqual(response.status_code, 302) |
| 1409 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 1410 |
# get a bare client |
| 1411 |
client = Client() |
| 1412 |
# requesting validation with a good (ticket, service) |
| 1413 |
response = client.get( |
| 1414 |
'/serviceValidate', |
| 1415 |
{'ticket': ticket_value, 'service': self.service} |
| 1416 |
) |
| 1417 |
# the validation should succes with username settings.CAS_TEST_USER and transmit |
| 1418 |
# the attributes settings.CAS_TEST_ATTRIBUTES |
| 1419 |
self.assert_success(response, settings.CAS_TEST_USER, settings.CAS_TEST_ATTRIBUTES) |
| 1420 |
|
| 1421 |
# case 3, client is not renewing and service ask for renew (client is authenticated) |
| 1422 |
response = client2.get("/login", {"service": self.service}) |
| 1423 |
self.assertEqual(response.status_code, 302) |
| 1424 |
ticket_value = response['Location'].split('ticket=')[-1] |
| 1425 |
client = Client() |
| 1426 |
# requesting validation with a good (ticket, service) |
| 1427 |
response = client.get( |
| 1428 |
'/serviceValidate', |
| 1429 |
{'ticket': ticket_value, 'service': self.service, 'renew': 'True'} |
| 1430 |
) |
| 1431 |
# the validation should fail |
| 1432 |
self.assert_error( |
| 1433 |
response, |
| 1434 |
"INVALID_TICKET", |
| 1435 |
'ticket not found' |
| 1436 |
) |
| 1437 |
|
| 1438 |
def test_validate_service_view_ok_one_attribute(self): |
| 1439 |
""" |
| 1440 |
test with a valid (ticket, service), the username and |
| 1441 |
the 'nom' only attribute are transmited |
| 1442 |
""" |
| 1443 |
# get a ticket for a service that transmit only one attribute |
| 1444 |
ticket = get_user_ticket_request(self.service_one_attribute)[1] |
| 1445 |
|
| 1446 |
client = Client() |
| 1447 |
response = client.get( |
| 1448 |
'/serviceValidate', |
| 1449 |
{'ticket': ticket.value, 'service': self.service_one_attribute} |
| 1450 |
) |
| 1451 |
# the validation should succed, returning settings.CAS_TEST_USER as username and a single |
| 1452 |
# attribute 'nom' |
| 1453 |
self.assert_success( |
| 1454 |
response, |
| 1455 |
settings.CAS_TEST_USER, |
| 1456 |
{'nom': settings.CAS_TEST_ATTRIBUTES['nom']} |
| 1457 |
) |
| 1458 |
|
| 1459 |
def test_validate_replace_attributes(self): |
| 1460 |
"""test with a valid (ticket, service), attributes name and value replacement""" |
| 1461 |
# get a ticket for a service pattern replacing attributes names |
| 1462 |
# nom -> NOM and value nom -> s/^N/P/ for a single valued attribute |
| 1463 |
ticket = get_user_ticket_request(self.service_replace_attribute)[1] |
| 1464 |
client = Client() |
| 1465 |
response = client.get( |
| 1466 |
'/serviceValidate', |
| 1467 |
{'ticket': ticket.value, 'service': self.service_replace_attribute} |
| 1468 |
) |
| 1469 |
self.assert_success( |
| 1470 |
response, |
| 1471 |
settings.CAS_TEST_USER, |
| 1472 |
{'NOM': 'Pymous'} |
| 1473 |
) |
| 1474 |
|
| 1475 |
# get a ticket for a service pattern replacing attributes names |
| 1476 |
# alias -> ALIAS and value alias -> s/demo/truc/ for a multi valued attribute |
| 1477 |
ticket = get_user_ticket_request(self.service_replace_attribute_list)[1] |
| 1478 |
client = Client() |
| 1479 |
response = client.get( |
| 1480 |
'/serviceValidate', |
| 1481 |
{'ticket': ticket.value, 'service': self.service_replace_attribute_list} |
| 1482 |
) |
| 1483 |
self.assert_success( |
| 1484 |
response, |
| 1485 |
settings.CAS_TEST_USER, |
| 1486 |
{'ALIAS': ['truc1', 'truc2']} |
| 1487 |
) |
| 1488 |
|
| 1489 |
def test_validate_service_view_badservice(self): |
| 1490 |
"""test with a valid ticket but a bad service, the validatin should fail""" |
| 1491 |
# get a ticket for service A |
| 1492 |
ticket = get_user_ticket_request(self.service)[1] |
| 1493 |
|
| 1494 |
client = Client() |
| 1495 |
bad_service = "https://www.example.org" |
| 1496 |
# try to validate it for service B |
| 1497 |
response = client.get('/serviceValidate', {'ticket': ticket.value, 'service': bad_service}) |
| 1498 |
# the validation should fail with error code "INVALID_SERVICE" |
| 1499 |
self.assert_error( |
| 1500 |
response, |
| 1501 |
"INVALID_SERVICE", |
| 1502 |
bad_service |
| 1503 |
) |
| 1504 |
|
| 1505 |
def test_validate_service_view_badticket_goodprefix(self): |
| 1506 |
""" |
| 1507 |
test with a good service but a bad ticket begining with ST-, |
| 1508 |
the validation should fail with the error (INVALID_TICKET, ticket not found) |
| 1509 |
""" |
| 1510 |
get_user_ticket_request(self.service) |
| 1511 |
|
| 1512 |
client = Client() |
| 1513 |
bad_ticket = "%s-RANDOM" % settings.CAS_SERVICE_TICKET_PREFIX |
| 1514 |
response = client.get('/serviceValidate', {'ticket': bad_ticket, 'service': self.service}) |
| 1515 |
self.assert_error( |
| 1516 |
response, |
| 1517 |
"INVALID_TICKET", |
| 1518 |
'ticket not found' |
| 1519 |
) |
| 1520 |
|
| 1521 |
def test_validate_service_view_badticket_badprefix(self): |
| 1522 |
""" |
| 1523 |
test with a good service bud a bad ticket not begining with ST-, |
| 1524 |
the validation should fail with the error (INVALID_TICKET, `the ticket`) |
| 1525 |
""" |
| 1526 |
get_user_ticket_request(self.service) |
| 1527 |
|
| 1528 |
client = Client() |
| 1529 |
bad_ticket = "RANDOM" |
| 1530 |
response = client.get('/serviceValidate', {'ticket': bad_ticket, 'service': self.service}) |
| 1531 |
self.assert_error( |
| 1532 |
response, |
| 1533 |
"INVALID_TICKET", |
| 1534 |
bad_ticket |
| 1535 |
) |
| 1536 |
|
| 1537 |
def test_validate_service_view_ok_pgturl(self): |
| 1538 |
"""test the retrieval of a ProxyGrantingTicket""" |
| 1539 |
# start a simple on request http server |
| 1540 |
(httpd, host, port) = HttpParamsHandler.run()[0:3] |
| 1541 |
# construct the service from it |
| 1542 |
service = "http://%s:%s" % (host, port) |
| 1543 |
|
| 1544 |
# get a ticket to be validated |
| 1545 |
ticket = get_user_ticket_request(service)[1] |
| 1546 |
|
| 1547 |
client = Client() |
| 1548 |
# request a PGT ticket then validating the ticket by setting the pgtUrl parameter |
| 1549 |
response = client.get( |
| 1550 |
'/serviceValidate', |
| 1551 |
{'ticket': ticket.value, 'service': service, 'pgtUrl': service} |
| 1552 |
) |
| 1553 |
# We should have recieved the PGT via a GET request parameter on the simple http server |
| 1554 |
pgt_params = httpd.PARAMS |
| 1555 |
self.assertEqual(response.status_code, 200) |
| 1556 |
|
| 1557 |
root = etree.fromstring(response.content) |
| 1558 |
# the validation response should return a id to match again the request transmitting the PGT |
| 1559 |
pgtiou = root.xpath( |
| 1560 |
"//cas:proxyGrantingTicket", |
| 1561 |
namespaces={'cas': "http://www.yale.edu/tp/cas"} |
| 1562 |
) |
| 1563 |
self.assertEqual(len(pgtiou), 1) |
| 1564 |
# the matching id for making corresponde one PGT to a validatin response should match |
| 1565 |
self.assertEqual(pgt_params["pgtIou"], pgtiou[0].text) |
| 1566 |
# the PGT is present in the receive GET requests parameters |
| 1567 |
self.assertTrue("pgtId" in pgt_params) |
| 1568 |
|
| 1569 |
def test_validate_service_pgturl_sslerror(self): |
| 1570 |
"""test the retrieval of a ProxyGrantingTicket with a SSL error on the pgtUrl""" |
| 1571 |
(host, port) = HttpParamsHandler.run()[1:3] |
| 1572 |
# is fact the service listen on http and not https raisin a SSL Protocol Error |
| 1573 |
# but other SSL/TLS error should behave the same |
| 1574 |
service = "https://%s:%s" % (host, port) |
| 1575 |
|
| 1576 |
ticket = get_user_ticket_request(service)[1] |
| 1577 |
|
| 1578 |
client = Client() |
| 1579 |
response = client.get( |
| 1580 |
'/serviceValidate', |
| 1581 |
{'ticket': ticket.value, 'service': service, 'pgtUrl': service} |
| 1582 |
) |
| 1583 |
# The pgtUrl is validated: it must be localhost or have valid x509 certificat and |
| 1584 |
# certificat validation should succed. Moreother, pgtUrl should match a service pattern |
| 1585 |
# with proxy_callback set to True |
| 1586 |
self.assert_error( |
| 1587 |
response, |
| 1588 |
"INVALID_PROXY_CALLBACK", |
| 1589 |
) |
| 1590 |
|
| 1591 |
def test_validate_service_pgturl_404(self): |
| 1592 |
""" |
| 1593 |
test the retrieval on a ProxyGrantingTicket then to pgtUrl return a http error. |
| 1594 |
PGT creation should be aborted but the ticket still be valid |
| 1595 |
""" |
| 1596 |
(host, port) = Http404Handler.run()[1:3] |
| 1597 |
service = "http://%s:%s" % (host, port) |
| 1598 |
|
| 1599 |
ticket = get_user_ticket_request(service)[1] |
| 1600 |
client = Client() |
| 1601 |
response = client.get( |
| 1602 |
'/serviceValidate', |
| 1603 |
{'ticket': ticket.value, 'service': service, 'pgtUrl': service} |
| 1604 |
) |
| 1605 |
# The ticket is successfully validated |
| 1606 |
root = self.assert_success(response, settings.CAS_TEST_USER, settings.CAS_TEST_ATTRIBUTES) |
| 1607 |
# but no PGT is transmitted |
| 1608 |
pgtiou = root.xpath( |
| 1609 |
"//cas:proxyGrantingTicket", |
| 1610 |
namespaces={'cas': "http://www.yale.edu/tp/cas"} |
| 1611 |
) |
| 1612 |
self.assertFalse(pgtiou) |
| 1613 |
|
| 1614 |
def test_validate_service_pgturl_bad_proxy_callback(self): |
| 1615 |
"""test the retrieval of a ProxyGrantingTicket, not allowed pgtUrl should be denied""" |
| 1616 |
self.service_pattern.proxy_callback = False |
| 1617 |
self.service_pattern.save() |
| 1618 |
ticket = get_user_ticket_request(self.service)[1] |
| 1619 |
client = Client() |
| 1620 |
response = client.get( |
| 1621 |
'/serviceValidate', |
| 1622 |
{'ticket': ticket.value, 'service': self.service, 'pgtUrl': self.service} |
| 1623 |
) |
| 1624 |
self.assert_error( |
| 1625 |
response, |
| 1626 |
"INVALID_PROXY_CALLBACK", |
| 1627 |
"callback url not allowed by configuration" |
| 1628 |
) |
| 1629 |
|
| 1630 |
self.service_pattern.proxy_callback = True |
| 1631 |
|
| 1632 |
ticket = get_user_ticket_request(self.service)[1] |
| 1633 |
client = Client() |
| 1634 |
response = client.get( |
| 1635 |
'/serviceValidate', |
| 1636 |
{'ticket': ticket.value, 'service': self.service, 'pgtUrl': "https://www.example.org"} |
| 1637 |
) |
| 1638 |
self.assert_error( |
| 1639 |
response, |
| 1640 |
"INVALID_PROXY_CALLBACK", |
| 1641 |
"callback url not allowed by configuration" |
| 1642 |
) |
| 1643 |
|
| 1644 |
def test_validate_user_field_ok(self): |
| 1645 |
""" |
| 1646 |
test with a good user_field. A bad user_field (that evaluate to False) |
| 1647 |
wont happed cause it is filtered in the login view |
| 1648 |
""" |
| 1649 |
for (service, username) in [ |
| 1650 |
(self.service_user_field, settings.CAS_TEST_ATTRIBUTES["alias"][0]), |
| 1651 |
(self.service_user_field_alt, settings.CAS_TEST_ATTRIBUTES["nom"]) |
| 1652 |
]: |
| 1653 |
# requesting a ticket for a service url matched by a service pattern using a user |
| 1654 |
# attribute as username |
| 1655 |
ticket = get_user_ticket_request(service)[1] |
| 1656 |
client = Client() |
| 1657 |
response = client.get( |
| 1658 |
'/serviceValidate', |
| 1659 |
{'ticket': ticket.value, 'service': service} |
| 1660 |
) |
| 1661 |
# The validate shoudl be successful with specified username and no attributes transmited |
| 1662 |
self.assert_success( |
| 1663 |
response, |
| 1664 |
username, |
| 1665 |
{} |
| 1666 |
) |
| 1667 |
|
| 1668 |
def test_validate_missing_parameter(self): |
| 1669 |
"""test with a missing GET parameter among [service, ticket]""" |
| 1670 |
ticket = get_user_ticket_request(self.service)[1] |
| 1671 |
|
| 1672 |
client = Client() |
| 1673 |
params = {'ticket': ticket.value, 'service': self.service} |
| 1674 |
for key in ['ticket', 'service']: |
| 1675 |
send_params = params.copy() |
| 1676 |
del send_params[key] |
| 1677 |
response = client.get('/serviceValidate', send_params) |
| 1678 |
# a validation request with a missing GET parameter should fail |
| 1679 |
self.assert_error( |
| 1680 |
response, |
| 1681 |
"INVALID_REQUEST", |
| 1682 |
"you must specify a service and a ticket" |
| 1683 |
) |
| 1684 |
|
| 1685 |
|
| 1686 |
@override_settings(CAS_AUTH_CLASS='cas_server.auth.TestAuthUser') |
| 1687 |
class ProxyTestCase(TestCase, BaseServicePattern, XmlContent): |
| 1688 |
"""tests for the proxy view""" |
| 1689 |
def setUp(self): |
| 1690 |
"""preparing test context""" |
| 1691 |
# we prepare a bunch a service url and service patterns for tests |
| 1692 |
self.setup_service_patterns(proxy=True) |
| 1693 |
|
| 1694 |
# set the default service pattern to localhost to be able to retrieve PGT |
| 1695 |
self.service = 'http://127.0.0.1' |
| 1696 |
self.service_pattern = models.ServicePattern.objects.create( |
| 1697 |
name="localhost", |
| 1698 |
pattern=r"^http://127\.0\.0\.1(:[0-9]+)?(/.*)?$", |
| 1699 |
proxy=True, |
| 1700 |
proxy_callback=True |
| 1701 |
) |
| 1702 |
# transmit all attributes |
| 1703 |
models.ReplaceAttributName.objects.create(name="*", service_pattern=self.service_pattern) |
| 1704 |
|
| 1705 |
def test_validate_proxy_ok(self): |
| 1706 |
""" |
| 1707 |
Get a PGT, get a proxy ticket, validate it. Validation should succeed and |
| 1708 |
show the proxy service URL. |
| 1709 |
""" |
| 1710 |
# we directrly get a ProxyGrantingTicket |
| 1711 |
params = get_pgt() |
| 1712 |
|
| 1713 |
# We try get a proxy ticket with our PGT |
| 1714 |
client1 = Client() |
| 1715 |
# for what we send a GET request to /proxy with ge PGT and the target service for which |
| 1716 |
# we want a ProxyTicket to. |
| 1717 |
response = client1.get( |
| 1718 |
'/proxy', |
| 1719 |
{'pgt': params['pgtId'], 'targetService': "https://www.example.com"} |
| 1720 |
) |
| 1721 |
self.assertEqual(response.status_code, 200) |
| 1722 |
|
| 1723 |
# we should sucessfully reteive a PT |
| 1724 |
root = etree.fromstring(response.content) |
| 1725 |
sucess = root.xpath("//cas:proxySuccess", namespaces={'cas': "http://www.yale.edu/tp/cas"}) |
| 1726 |
self.assertTrue(sucess) |
| 1727 |
|
| 1728 |
proxy_ticket = root.xpath( |
| 1729 |
"//cas:proxyTicket", |
| 1730 |
namespaces={'cas': "http://www.yale.edu/tp/cas"} |
| 1731 |
) |
| 1732 |
self.assertEqual(len(proxy_ticket), 1) |
| 1733 |
proxy_ticket = proxy_ticket[0].text |
| 1734 |
|
| 1735 |
# validate the proxy ticket with the service for which is was emitted |
| 1736 |
client2 = Client() |
| 1737 |
response = client2.get( |
| 1738 |
'/proxyValidate', |
| 1739 |
{'ticket': proxy_ticket, 'service': "https://www.example.com"} |
| 1740 |
) |
| 1741 |
# validation should succeed and return settings.CAS_TEST_USER as username |
| 1742 |
# and settings.CAS_TEST_ATTRIBUTES as attributes |
| 1743 |
root = self.assert_success( |
| 1744 |
response, |
| 1745 |
settings.CAS_TEST_USER, |
| 1746 |
settings.CAS_TEST_ATTRIBUTES |
| 1747 |
) |
| 1748 |
|
| 1749 |
# in the PT validation response, it should have the service url of the PGY |
| 1750 |
proxies = root.xpath("//cas:proxies", namespaces={'cas': "http://www.yale.edu/tp/cas"}) |
| 1751 |
self.assertEqual(len(proxies), 1) |
| 1752 |
proxy = proxies[0].xpath("//cas:proxy", namespaces={'cas': "http://www.yale.edu/tp/cas"}) |
| 1753 |
self.assertEqual(len(proxy), 1) |
| 1754 |
self.assertEqual(proxy[0].text, params["service"]) |
| 1755 |
|
| 1756 |
def test_validate_proxy_bad_pgt(self): |
| 1757 |
"""Try to get a ProxyTicket with a bad PGT. The PT generation should fail""" |
| 1758 |
# we directrly get a ProxyGrantingTicket |
| 1759 |
params = get_pgt() |
| 1760 |
client = Client() |
| 1761 |
response = client.get( |
| 1762 |
'/proxy', |
| 1763 |
{ |
| 1764 |
'pgt': "%s-RANDOM" % settings.CAS_PROXY_GRANTING_TICKET_PREFIX, |
| 1765 |
'targetService': params['service'] |
| 1766 |
} |
| 1767 |
) |
| 1768 |
self.assert_error( |
| 1769 |
response, |
| 1770 |
"INVALID_TICKET", |
| 1771 |
"PGT %s-RANDOM not found" % settings.CAS_PROXY_GRANTING_TICKET_PREFIX |
| 1772 |
) |
| 1773 |
|
| 1774 |
def test_validate_proxy_bad_service(self): |
| 1775 |
""" |
| 1776 |
Try to get a ProxyTicket for a denied service and |
| 1777 |
a service that do not allow PT. The PT generation should fail. |
| 1778 |
""" |
| 1779 |
# we directrly get a ProxyGrantingTicket |
| 1780 |
params = get_pgt() |
| 1781 |
|
| 1782 |
# try to get a PT for a denied service |
| 1783 |
client1 = Client() |
| 1784 |
response = client1.get( |
| 1785 |
'/proxy', |
| 1786 |
{'pgt': params['pgtId'], 'targetService': "https://www.example.org"} |
| 1787 |
) |
| 1788 |
self.assert_error( |
| 1789 |
response, |
| 1790 |
"UNAUTHORIZED_SERVICE", |
| 1791 |
"https://www.example.org" |
| 1792 |
) |
| 1793 |
|
| 1794 |
# try to get a PT for a service that do not allow PT |
| 1795 |
self.service_pattern.proxy = False |
| 1796 |
self.service_pattern.save() |
| 1797 |
|
| 1798 |
client2 = Client() |
| 1799 |
response = client2.get( |
| 1800 |
'/proxy', |
| 1801 |
{'pgt': params['pgtId'], 'targetService': params['service']} |
| 1802 |
) |
| 1803 |
|
| 1804 |
self.assert_error( |
| 1805 |
response, |
| 1806 |
"UNAUTHORIZED_SERVICE", |
| 1807 |
'the service %s does not allow proxy tickets' % params['service'] |
| 1808 |
) |
| 1809 |
|
| 1810 |
self.service_pattern.proxy = True |
| 1811 |
self.service_pattern.save() |
| 1812 |
|
| 1813 |
def test_proxy_unauthorized_user(self): |
| 1814 |
""" |
| 1815 |
Try to get a PT for services that do not allow the current user: |
| 1816 |
* first with a service that restrict allowed username |
| 1817 |
* second with a service requiring somes conditions on the user attributes |
| 1818 |
* third with a service using a particular user attribute as username |
| 1819 |
All this tests should fail |
| 1820 |
""" |
| 1821 |
# we directrly get a ProxyGrantingTicket |
| 1822 |
params = get_pgt() |
| 1823 |
|
| 1824 |
for service in [ |
| 1825 |
# do ot allow the test username |
| 1826 |
self.service_restrict_user_fail, |
| 1827 |
# require the 'nom' attribute to be 'toto' |
| 1828 |
self.service_filter_fail, |
| 1829 |
# want to use the non-exitant 'uid' attribute as username |
| 1830 |
self.service_field_needed_fail |
| 1831 |
]: |
| 1832 |
client = Client() |
| 1833 |
response = client.get( |
| 1834 |
'/proxy', |
| 1835 |
{'pgt': params['pgtId'], 'targetService': service} |
| 1836 |
) |
| 1837 |
# PT generation should fail |
| 1838 |
self.assert_error( |
| 1839 |
response, |
| 1840 |
"UNAUTHORIZED_USER", |
| 1841 |
'User %s not allowed on %s' % (settings.CAS_TEST_USER, service) |
| 1842 |
) |
| 1843 |
|
| 1844 |
def test_proxy_missing_parameter(self): |
| 1845 |
"""Try to get a PGT with some missing GET parameters. The PT should not be emited""" |
| 1846 |
params = get_pgt() |
| 1847 |
base_params = {'pgt': params['pgtId'], 'targetService': "https://www.example.org"} |
| 1848 |
for key in ["pgt", 'targetService']: |
| 1849 |
send_params = base_params.copy() |
| 1850 |
del send_params[key] |
| 1851 |
client = Client() |
| 1852 |
response = client.get("/proxy", send_params) |
| 1853 |
self.assert_error( |
| 1854 |
response, |
| 1855 |
"INVALID_REQUEST", |
| 1856 |
'you must specify and pgt and targetService' |
| 1857 |
) |
| 1858 |
|
| 1859 |
|
| 1860 |
@override_settings(CAS_AUTH_CLASS='cas_server.auth.TestAuthUser') |
| 1861 |
class SamlValidateTestCase(TestCase, BaseServicePattern, XmlContent): |
| 1862 |
"""tests for the proxy view""" |
| 1863 |
def setUp(self): |
| 1864 |
"""preparing test context""" |
| 1865 |
# we prepare a bunch a service url and service patterns for tests |
| 1866 |
self.setup_service_patterns(proxy=True) |
| 1867 |
|
| 1868 |
# special service pattern for retrieving a PGT |
| 1869 |
self.service_pgt = 'http://127.0.0.1' |
| 1870 |
self.service_pattern_pgt = models.ServicePattern.objects.create( |
| 1871 |
name="localhost", |
| 1872 |
pattern=r"^http://127\.0\.0\.1(:[0-9]+)?(/.*)?$", |
| 1873 |
proxy=True, |
| 1874 |
proxy_callback=True |
| 1875 |
) |
| 1876 |
models.ReplaceAttributName.objects.create( |
| 1877 |
name="*", |
| 1878 |
service_pattern=self.service_pattern_pgt |
| 1879 |
) |
| 1880 |
|
| 1881 |
# template for the XML POST need to be send to validate a ticket using SAML 1.1 |
| 1882 |
xml_template = """ |
| 1883 |
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> |
| 1884 |
<SOAP-ENV:Header/> |
| 1885 |
<SOAP-ENV:Body> |
| 1886 |
<samlp:Request |
| 1887 |
xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" |
| 1888 |
MajorVersion="1" MinorVersion="1" |
| 1889 |
RequestID="%(request_id)s" |
| 1890 |
IssueInstant="%(issue_instant)s" |
| 1891 |
> |
| 1892 |
<samlp:AssertionArtifact>%(ticket)s</samlp:AssertionArtifact> |
| 1893 |
</samlp:Request> |
| 1894 |
</SOAP-ENV:Body> |
| 1895 |
</SOAP-ENV:Envelope>""" |
| 1896 |
|
| 1897 |
def assert_success(self, response, username, original_attributes): |
| 1898 |
"""assert ticket validation success""" |
| 1899 |
self.assertEqual(response.status_code, 200) |
| 1900 |
# on validation success, the response should have a StatusCode set to Success |
| 1901 |
root = etree.fromstring(response.content) |
| 1902 |
success = root.xpath( |
| 1903 |
"//samlp:StatusCode", |
| 1904 |
namespaces={'samlp': "urn:oasis:names:tc:SAML:1.0:protocol"} |
| 1905 |
) |
| 1906 |
self.assertEqual(len(success), 1) |
| 1907 |
self.assertTrue(success[0].attrib['Value'].endswith(":Success")) |
| 1908 |
|
| 1909 |
# the user username should be return whithin <NameIdentifier> tags |
| 1910 |
user = root.xpath( |
| 1911 |
"//samla:NameIdentifier", |
| 1912 |
namespaces={'samla': "urn:oasis:names:tc:SAML:1.0:assertion"} |
| 1913 |
) |
| 1914 |
self.assertTrue(user) |
| 1915 |
self.assertEqual(user[0].text, username) |
| 1916 |
|
| 1917 |
# the returned attributes should match original_attributes |
| 1918 |
attributes = root.xpath( |
| 1919 |
"//samla:AttributeStatement/samla:Attribute", |
| 1920 |
namespaces={'samla': "urn:oasis:names:tc:SAML:1.0:assertion"} |
| 1921 |
) |
| 1922 |
ignore_attrs = { |
| 1923 |
"authenticationDate", "longTermAuthenticationRequestTokenUsed", "isFromNewLogin" |
| 1924 |
} - set(original_attributes.keys()) |
| 1925 |
attrs = set() |
| 1926 |
for attr in attributes: |
| 1927 |
if not attr.attrib['AttributeName'] in ignore_attrs: |
| 1928 |
attrs.add((attr.attrib['AttributeName'], attr.getchildren()[0].text)) |
| 1929 |
original = set() |
| 1930 |
for key, value in original_attributes.items(): |
| 1931 |
if isinstance(value, list): |
| 1932 |
for subval in value: |
| 1933 |
original.add((key, subval)) |
| 1934 |
else: |
| 1935 |
original.add((key, value)) |
| 1936 |
self.assertEqual(original, attrs) |
| 1937 |
|
| 1938 |
def assert_error(self, response, code, msg=None): |
| 1939 |
"""assert ticket validation error""" |
| 1940 |
self.assertEqual(response.status_code, 200) |
| 1941 |
# on error the status code value should be the one provider in `code` |
| 1942 |
root = etree.fromstring(response.content) |
| 1943 |
error = root.xpath( |
| 1944 |
"//samlp:StatusCode", |
| 1945 |
namespaces={'samlp': "urn:oasis:names:tc:SAML:1.0:protocol"} |
| 1946 |
) |
| 1947 |
self.assertEqual(len(error), 1) |
| 1948 |
self.assertTrue(error[0].attrib['Value'].endswith(":%s" % code)) |
| 1949 |
# it may have an error message |
| 1950 |
if msg is not None: |
| 1951 |
self.assertEqual(error[0].text, msg) |
| 1952 |
|
| 1953 |
def test_saml_ok(self): |
| 1954 |
""" |
| 1955 |
test with a valid (ticket, service), with a ST and a PT, |
| 1956 |
the username and all attributes are transmited""" |
| 1957 |
tickets = [ |
| 1958 |
# return a ServiceTicket (standard ticket) waiting for validation |
| 1959 |
get_user_ticket_request(self.service)[1], |
| 1960 |
# return a PT waiting for validation |
| 1961 |
get_proxy_ticket(self.service) |
| 1962 |
] |
| 1963 |
|
| 1964 |
for ticket in tickets: |
| 1965 |
client = Client() |
| 1966 |
# we send the POST validation requests |
| 1967 |
response = client.post( |
| 1968 |
'/samlValidate?TARGET=%s' % self.service, |
| 1969 |
self.xml_template % { |
| 1970 |
'ticket': ticket.value, |
| 1971 |
'request_id': utils.gen_saml_id(), |
| 1972 |
'issue_instant': timezone.now().isoformat() |
| 1973 |
}, |
| 1974 |
content_type="text/xml; encoding='utf-8'" |
| 1975 |
) |
| 1976 |
# and it should succeed |
| 1977 |
self.assert_success(response, settings.CAS_TEST_USER, settings.CAS_TEST_ATTRIBUTES) |
| 1978 |
|
| 1979 |
def test_saml_ok_user_field(self): |
| 1980 |
"""test with a valid(ticket, service), use a attributes as transmitted username""" |
| 1981 |
for (service, username) in [ |
| 1982 |
(self.service_field_needed_success, settings.CAS_TEST_ATTRIBUTES['alias'][0]), |
| 1983 |
(self.service_field_needed_success_alt, settings.CAS_TEST_ATTRIBUTES['nom']) |
| 1984 |
]: |
| 1985 |
ticket = get_user_ticket_request(service)[1] |
| 1986 |
|
| 1987 |
client = Client() |
| 1988 |
response = client.post( |
| 1989 |
'/samlValidate?TARGET=%s' % service, |
| 1990 |
self.xml_template % { |
| 1991 |
'ticket': ticket.value, |
| 1992 |
'request_id': utils.gen_saml_id(), |
| 1993 |
'issue_instant': timezone.now().isoformat() |
| 1994 |
}, |
| 1995 |
content_type="text/xml; encoding='utf-8'" |
| 1996 |
) |
| 1997 |
self.assert_success(response, username, {}) |
| 1998 |
|
| 1999 |
def test_saml_bad_ticket(self): |
| 2000 |
"""test validation with a bad ST and a bad PT, validation should fail""" |
| 2001 |
tickets = [utils.gen_st(), utils.gen_pt()] |
| 2002 |
|
| 2003 |
for ticket in tickets: |
| 2004 |
client = Client() |
| 2005 |
response = client.post( |
| 2006 |
'/samlValidate?TARGET=%s' % self.service, |
| 2007 |
self.xml_template % { |
| 2008 |
'ticket': ticket, |
| 2009 |
'request_id': utils.gen_saml_id(), |
| 2010 |
'issue_instant': timezone.now().isoformat() |
| 2011 |
}, |
| 2012 |
content_type="text/xml; encoding='utf-8'" |
| 2013 |
) |
| 2014 |
self.assert_error( |
| 2015 |
response, |
| 2016 |
"AuthnFailed", |
| 2017 |
'ticket %s not found' % ticket |
| 2018 |
) |
| 2019 |
|
| 2020 |
def test_saml_bad_ticket_prefix(self): |
| 2021 |
"""test validation with a bad ticket prefix. Validation should fail with 'AuthnFailed'""" |
| 2022 |
bad_ticket = "RANDOM-NOT-BEGINING-WITH-ST-OR-ST" |
| 2023 |
client = Client() |
| 2024 |
response = client.post( |
| 2025 |
'/samlValidate?TARGET=%s' % self.service, |
| 2026 |
self.xml_template % { |
| 2027 |
'ticket': bad_ticket, |
| 2028 |
'request_id': utils.gen_saml_id(), |
| 2029 |
'issue_instant': timezone.now().isoformat() |
| 2030 |
}, |
| 2031 |
content_type="text/xml; encoding='utf-8'" |
| 2032 |
) |
| 2033 |
self.assert_error( |
| 2034 |
response, |
| 2035 |
"AuthnFailed", |
| 2036 |
'ticket %s should begin with PT- or ST-' % bad_ticket |
| 2037 |
) |
| 2038 |
|
| 2039 |
def test_saml_bad_target(self): |
| 2040 |
"""test with a valid ticket, but using a bad target, validation should fail""" |
| 2041 |
bad_target = "https://www.example.org" |
| 2042 |
ticket = get_user_ticket_request(self.service)[1] |
| 2043 |
|
| 2044 |
client = Client() |
| 2045 |
response = client.post( |
| 2046 |
'/samlValidate?TARGET=%s' % bad_target, |
| 2047 |
self.xml_template % { |
| 2048 |
'ticket': ticket.value, |
| 2049 |
'request_id': utils.gen_saml_id(), |
| 2050 |
'issue_instant': timezone.now().isoformat() |
| 2051 |
}, |
| 2052 |
content_type="text/xml; encoding='utf-8'" |
| 2053 |
) |
| 2054 |
self.assert_error( |
| 2055 |
response, |
| 2056 |
"AuthnFailed", |
| 2057 |
'TARGET %s does not match ticket service' % bad_target |
| 2058 |
) |
| 2059 |
|
| 2060 |
def test_saml_bad_xml(self): |
| 2061 |
"""test validation with a bad xml request, validation should fail""" |
| 2062 |
client = Client() |
| 2063 |
response = client.post( |
| 2064 |
'/samlValidate?TARGET=%s' % self.service, |
| 2065 |
"<root></root>", |
| 2066 |
content_type="text/xml; encoding='utf-8'" |
| 2067 |
) |
| 2068 |
self.assert_error(response, 'VersionMismatch') |