authentik.providers.saml.tests.test_auth_n_request
Test AuthN Request generator and parser
1"""Test AuthN Request generator and parser""" 2 3import tracemalloc 4from base64 import b64encode 5from json import loads 6from unittest.mock import patch 7from urllib.parse import parse_qs, urlparse 8 9from defusedxml.lxml import fromstring 10from django.http.request import QueryDict 11from django.test import TestCase 12from django.urls import reverse 13from guardian.utils import get_anonymous_user 14from lxml import etree # nosec 15 16from authentik.admin.flags import patch_flag 17from authentik.blueprints.tests import apply_blueprint 18from authentik.common.saml.constants import ( 19 AES128_CBC, 20 AES128_GCM, 21 AES256_CBC, 22 AES256_GCM, 23 NS_MAP, 24 SAML_BINDING_POST, 25 SAML_NAME_ID_FORMAT_EMAIL, 26 SAML_NAME_ID_FORMAT_UNSPECIFIED, 27) 28from authentik.common.saml.exceptions import ( 29 ERROR_ACS_URL_MISMATCH, 30 ERROR_CANNOT_DECODE_REQUEST, 31 CannotHandleAssertion, 32) 33from authentik.core.models import Application 34from authentik.core.tests.utils import ( 35 RequestFactory, 36 create_test_admin_user, 37 create_test_cert, 38 create_test_flow, 39) 40from authentik.crypto.models import CertificateKeyPair 41from authentik.events.models import Event, EventAction 42from authentik.flows.apps import ContinuousLogin 43from authentik.flows.models import FlowStageBinding 44from authentik.flows.planner import PLAN_CONTEXT_APPLICATION 45from authentik.flows.views.executor import SESSION_KEY_GET, SESSION_KEY_PLAN 46from authentik.lib.generators import generate_id 47from authentik.lib.xml import lxml_from_string 48from authentik.policies.dummy.models import DummyPolicy 49from authentik.policies.models import PolicyBinding 50from authentik.providers.saml.models import ( 51 SAMLBindings, 52 SAMLPropertyMapping, 53 SAMLProvider, 54 SAMLSession, 55) 56from authentik.providers.saml.processors.assertion import AssertionProcessor 57from authentik.providers.saml.processors.authn_request_parser import AuthNRequestParser 58from authentik.providers.saml.utils.encoding import deflate_and_base64_encode 59from authentik.providers.saml.views.sso import SESSION_KEY_LAST_LOGIN_UID 60from authentik.sources.saml.exceptions import MismatchedRequestID, SAMLException 61from authentik.sources.saml.models import SAMLBindingTypes, SAMLSource 62from authentik.sources.saml.processors.request import SESSION_KEY_REQUEST_ID, RequestProcessor 63from authentik.sources.saml.processors.response import ResponseProcessor 64from authentik.stages.consent.models import ConsentStage 65from authentik.stages.dummy.models import DummyStage 66 67POST_REQUEST = ( 68 "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c2FtbDJwOkF1dGhuUmVxdWVzdCB4bWxuczpzYW1sMn" 69 "A9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpwcm90b2NvbCIgQXNzZXJ0aW9uQ29uc3VtZXJTZXJ2aWNlVVJMPSJo" 70 "dHRwczovL2V1LWNlbnRyYWwtMS5zaWduaW4uYXdzLmFtYXpvbi5jb20vcGxhdGZvcm0vc2FtbC9hY3MvMmQ3MzdmOTYtNT" 71 "VmYi00MDM1LTk1M2UtNWUyNDEzNGViNzc4IiBEZXN0aW5hdGlvbj0iaHR0cHM6Ly9pZC5iZXJ5anUub3JnL2FwcGxpY2F0" 72 "aW9uL3NhbWwvYXdzLXNzby9zc28vYmluZGluZy9wb3N0LyIgSUQ9ImF3c19MRHhMR2V1YnBjNWx4MTJneENnUzZ1UGJpeD" 73 "F5ZDVyZSIgSXNzdWVJbnN0YW50PSIyMDIxLTA3LTA2VDE0OjIzOjA2LjM4OFoiIFByb3RvY29sQmluZGluZz0idXJuOm9h" 74 "c2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmJpbmRpbmdzOkhUVFAtUE9TVCIgVmVyc2lvbj0iMi4wIj48c2FtbDI6SXNzdWVyIH" 75 "htbG5zOnNhbWwyPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIj5odHRwczovL2V1LWNlbnRyYWwt" 76 "MS5zaWduaW4uYXdzLmFtYXpvbi5jb20vcGxhdGZvcm0vc2FtbC9kLTk5NjcyZjgyNzg8L3NhbWwyOklzc3Vlcj48c2FtbD" 77 "JwOk5hbWVJRFBvbGljeSBGb3JtYXQ9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMTpuYW1laWQtZm9ybWF0OmVtYWls" 78 "QWRkcmVzcyIvPjwvc2FtbDJwOkF1dGhuUmVxdWVzdD4=" 79) 80REDIRECT_REQUEST = ( 81 "fZLNbsIwEIRfJfIdbKeFgEUipXAoEm0jSHvopTLJplhK7NTr9Oft6yRUKhekPdk73+yOdoWyqVuRdu6k9/DRAbrgu6k1iu" 82 "EjJp3VwkhUKLRsAIUrxCF92IlwykRrjTOFqUmQIoJ1yui10dg1YA9gP1UBz/tdTE7OtSgo5WzKQzYditGeP8GW9rSQZk+H" 83 "nAQbb6+07EGj7EI1j8SCeaVs21oVQ9dAoRqcf6OIhh6VLpV+pxZKZaFwlATbTUzeyqKazaqiDCO5WEQwZzKCagkwr8obWc" 84 "qjb0PsYKvRSe1iErKQTTj3lYdc3HLBl68kyM4L340u19M5j4LiPs+zybjgC1gclvMNJFn104vB2P5L/TpW/kVNkqvBrug/" 85 "+mjVikeP224y4/P7CdK6Nl9rC9JBTDihySi5vIbkFw==" 86) 87REDIRECT_SIGNATURE = ( 88 "UlOe1BItHVHM+io6rUZAenIqfibm7hM6wr9I1rcP5kPJ4N8cbkyqmAMh5LD2lUq3PDERJfjdO/oOKnvJmbD2y9MOObyR2d" 89 "7Udv62KERrA0qM917Q+w8wrLX7w2nHY96EDvkXD4iAomR5EE9dHRuubDy7uRv2syEevc0gfoLi7W/5vp96vJgsaSqxnTp+" 90 "QiYq49KyWyMtxRULF2yd+vYDnHCDME73mNSULEHfwCU71dvbKpnFaej78q7wS20gUk6ysOOXXtvDHbiVcpUb/9oyDgNAxU" 91 "jVvPdh96AhBFj2HCuGZhP0CGotafTciu6YlsiwUpuBkIYgZmNWYa3FR9LS4Q==" 92) 93REDIRECT_SIG_ALG = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" 94REDIRECT_RELAY_STATE = "ss:mem:7a054b4af44f34f89dd2d973f383c250b6b076e7f06cfa8276008a6504eaf3c7" 95REDIRECT_CERT = """-----BEGIN CERTIFICATE----- 96MIIDCDCCAfCgAwIBAgIRAM5s+bhOHk4ChSpPkGSh0NswDQYJKoZIhvcNAQELBQAw 97KzEpMCcGA1UEAwwgcGFzc2Jvb2sgU2VsZi1zaWduZWQgQ2VydGlmaWNhdGUwHhcN 98MjAxMTA3MjAzNDIxWhcNMjExMTA4MjAzNDIxWjBUMSkwJwYDVQQDDCBwYXNzYm9v 99ayBTZWxmLXNpZ25lZCBDZXJ0aWZpY2F0ZTERMA8GA1UECgwIcGFzc2Jvb2sxFDAS 100BgNVBAsMC1NlbGYtc2lnbmVkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC 101AQEAuh+Bv6a/ogpic72X/sq86YiLzVjixnGqjc4wpsPPP00GX8jUAZJL4Tjo+sYK 102IU2DF2/azlVqjkbLho4rGuuc8YkbFXBEXPYc5h3bseO2vk6sbbbWKV0mro1VFhBh 103T59hBORuMMefmQdhFzsRNOGklIptQdg0quD8ET3+/uNfIT98S2ruZdYteFls46Sa 104MokZFYVD6pWEYV4P2MKVAFqJX9bqBW0LfCCfFqHAOJjUZj9dtleg86d2WfedUOG2 105LK0iLrydjhThbI0GUDhv0jWYkRlv04fdJ1WSRANYA3gBOnyw+Iigh2xNnYbVZMXT 106I0BupIJ4UoODMc4QpD2GYJ6oGwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQCCEF3e 107Y99KxEBSR4H4/TvKbnh4QtHswOf7MaGdjtrld7l4u4Hc4NEklNdDn1XLKhZwnq3Z 108LRsRlJutDzZ18SRmAJPXPbka7z7D+LA1mbNQElOgiKyQHD9rIJSBr6X5SM9As3CR 1097QUsb8dg7kc+Jn7WuLZIEVxxMtekt0buWEdMJiklF0tCS3LNsP083FaQk/H1K0z6 1103PWP26EFdwir3RyTKLY5CBLjKrUAo9O1l/WBVFYbdetnipbGGu5f6nk6nnxbwLLI 111Dm52Vkq+xFDDUq9IqIoYvLaE86MDvtpMQEx65tIGU19vUf3fL/+sSfdRZ1HDzP4d 112qNAZMq1DqpibfCBg 113-----END CERTIFICATE-----""" 114 115 116class TestAuthNRequest(TestCase): 117 """Test AuthN Request generator and parser""" 118 119 @apply_blueprint("system/providers-saml.yaml") 120 def setUp(self): 121 self.request_factory = RequestFactory() 122 self.cert = create_test_cert() 123 self.provider: SAMLProvider = SAMLProvider.objects.create( 124 authorization_flow=create_test_flow(), 125 acs_url="http://testserver/source/saml/provider/acs/", 126 signing_kp=self.cert, 127 verification_kp=self.cert, 128 ) 129 self.provider.property_mappings.set(SAMLPropertyMapping.objects.all()) 130 self.provider.save() 131 Application.objects.create( 132 name="test-app", 133 slug="test-app", 134 provider=self.provider, 135 ) 136 self.source = SAMLSource.objects.create( 137 slug="provider", 138 issuer_override="authentik", 139 pre_authentication_flow=create_test_flow(), 140 signing_kp=self.cert, 141 verification_kp=self.cert, 142 signed_assertion=True, 143 binding_type=SAMLBindingTypes.POST, 144 ) 145 146 def post_authn_request(self, application_slug: str = "test-app", relay_state="test_state"): 147 """Send an SP-initiated AuthnRequest using the HTTP-POST binding.""" 148 request = RequestProcessor( 149 self.source, self.request_factory.get("/"), relay_state 150 ).build_auth_n() 151 return self.client.post( 152 reverse( 153 "authentik_providers_saml:sso-post", 154 kwargs={"application_slug": application_slug}, 155 ), 156 { 157 "SAMLRequest": b64encode(request.encode()).decode(), 158 "RelayState": relay_state, 159 }, 160 ) 161 162 def bind_excluded_consent_stage(self): 163 """Bind a consent stage to the authorization flow whose policy excludes every user 164 while the flow is planned.""" 165 binding = FlowStageBinding.objects.create( 166 target=self.provider.authorization_flow, 167 stage=ConsentStage.objects.create(name=generate_id()), 168 order=0, 169 evaluate_on_plan=True, 170 re_evaluate_policies=False, 171 ) 172 PolicyBinding.objects.create( 173 target=binding, 174 policy=DummyPolicy.objects.create( 175 name=generate_id(), result=False, wait_min=0, wait_max=1 176 ), 177 order=0, 178 ) 179 180 def executor_url(self, provider: SAMLProvider) -> str: 181 """Flow executor API URL for a provider's authorization flow.""" 182 return reverse( 183 "authentik_api:flow-executor", 184 kwargs={"flow_slug": provider.authorization_flow.slug}, 185 ) 186 187 def assert_direct_post_response(self, response): 188 """Assert a direct SAML HTTP-POST response and its side effects.""" 189 self.assertEqual(response.status_code, 200) 190 self.assertTemplateUsed(response, "if/saml_form_post.html") 191 self.assertEqual(response.context_data["redirect_uri"], self.provider.acs_url) 192 self.assertEqual(response.context_data["attrs"]["RelayState"], "test_state") 193 self.assertIn("SAMLResponse", response.context_data["attrs"]) 194 self.assertIn("no-store", response["Cache-Control"]) 195 self.assertEqual(response["Pragma"], "no-cache") 196 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 197 self.assertTrue(SAMLSession.objects.filter(provider=self.provider).exists()) 198 self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) 199 200 def test_post_response_empty_flow_is_direct(self): 201 """An empty authorization flow returns the SAML POST form directly.""" 202 self.provider.sp_binding = SAMLBindings.POST 203 self.provider.save() 204 self.client.force_login(create_test_admin_user()) 205 206 self.assert_direct_post_response(self.post_authn_request()) 207 208 def test_post_response_empty_flow_error_is_error_page(self): 209 """A direct SAML error renders an HTML error without exposing internal details.""" 210 self.provider.sp_binding = SAMLBindings.POST 211 self.provider.save() 212 self.client.force_login(create_test_admin_user()) 213 214 with patch.object( 215 AssertionProcessor, "build_response", side_effect=SAMLException("internal test error") 216 ): 217 response = self.post_authn_request() 218 219 self.assertEqual(response.status_code, 400) 220 self.assertTemplateUsed(response, "if/error.html") 221 self.assertContains(response, "Failed to process SAML assertion.", status_code=400) 222 self.assertNotContains(response, "internal test error", status_code=400) 223 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 224 self.assertFalse(SAMLSession.objects.filter(provider=self.provider).exists()) 225 self.assertTrue(Event.objects.filter(action=EventAction.CONFIGURATION_ERROR).exists()) 226 227 @patch_flag(ContinuousLogin, True) 228 def test_post_response_empty_flow_is_direct_with_continuous_login(self): 229 """Continuous login does not force an empty authorization flow into the executor.""" 230 self.provider.sp_binding = SAMLBindings.POST 231 self.provider.save() 232 self.client.force_login(create_test_admin_user()) 233 234 self.assert_direct_post_response(self.post_authn_request()) 235 236 @patch_flag(ContinuousLogin, True) 237 def test_redirect_response_empty_flow_is_direct_with_continuous_login(self): 238 """An empty authorization flow returns the SAML Redirect response directly.""" 239 self.provider.sp_binding = SAMLBindings.REDIRECT 240 self.provider.save() 241 app = Application.objects.get(slug="test-app") 242 params = RequestProcessor( 243 self.source, self.request_factory.get("/"), "test_state" 244 ).build_auth_n_detached() 245 self.client.force_login(create_test_admin_user()) 246 247 response = self.client.get( 248 reverse( 249 "authentik_providers_saml:sso-redirect", 250 kwargs={"application_slug": app.slug}, 251 ), 252 params, 253 ) 254 255 self.assertEqual(response.status_code, 302) 256 redirect = urlparse(response["Location"]) 257 self.assertEqual( 258 f"{redirect.scheme}://{redirect.netloc}{redirect.path}", self.provider.acs_url 259 ) 260 redirect_query = parse_qs(redirect.query) 261 self.assertEqual(redirect_query["RelayState"], ["test_state"]) 262 self.assertIn("SAMLResponse", redirect_query) 263 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 264 self.assertTrue(SAMLSession.objects.filter(provider=self.provider).exists()) 265 self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) 266 267 def test_post_response_nonempty_flow_uses_executor(self): 268 """A configured authorization stage keeps using the flow executor.""" 269 self.provider.sp_binding = SAMLBindings.POST 270 self.provider.save() 271 FlowStageBinding.objects.create( 272 target=self.provider.authorization_flow, 273 stage=DummyStage.objects.create(name=generate_id()), 274 order=0, 275 ) 276 self.client.force_login(create_test_admin_user()) 277 278 response = self.post_authn_request() 279 280 self.assertEqual(response.status_code, 302) 281 self.assertEqual( 282 urlparse(response["Location"]).path, 283 reverse( 284 "authentik_core:if-flow", 285 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 286 ), 287 ) 288 self.assertIn(SESSION_KEY_PLAN, self.client.session) 289 290 def test_post_response_excluded_stage_is_direct(self): 291 """A configured stage that policies exclude for this user doesn't need the executor.""" 292 self.provider.sp_binding = SAMLBindings.POST 293 self.provider.save() 294 self.bind_excluded_consent_stage() 295 self.client.force_login(create_test_admin_user()) 296 297 self.assert_direct_post_response(self.post_authn_request()) 298 299 @patch_flag(ContinuousLogin, True) 300 def test_post_response_excluded_stage_uses_executor_with_continuous_login(self): 301 """With continuous login, a configured stage keeps the response in the flow executor 302 even when policies exclude it, since other tabs were told to wait for this flow.""" 303 self.provider.sp_binding = SAMLBindings.POST 304 self.provider.save() 305 self.bind_excluded_consent_stage() 306 self.client.force_login(create_test_admin_user()) 307 308 response = self.post_authn_request() 309 310 self.assertEqual(response.status_code, 302) 311 self.assertEqual( 312 urlparse(response["Location"]).path, 313 reverse( 314 "authentik_core:if-flow", 315 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 316 ), 317 ) 318 self.assertFalse(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) 319 challenge = self.client.get(self.executor_url(self.provider)).json() 320 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 321 self.assertEqual(challenge["url"], self.provider.acs_url) 322 323 def test_post_to_executor_final_stage_does_not_reissue_assertion(self): 324 """A POST to the flow executor at the final stage keeps the challenge-response handling 325 instead of issuing another assertion.""" 326 self.provider.sp_binding = SAMLBindings.POST 327 self.provider.save() 328 FlowStageBinding.objects.create( 329 target=self.provider.authorization_flow, 330 stage=DummyStage.objects.create(name=generate_id()), 331 order=0, 332 ) 333 self.client.force_login(create_test_admin_user()) 334 self.post_authn_request() 335 executor_url = self.executor_url(self.provider) 336 self.client.get(executor_url) 337 self.client.post( 338 executor_url, {"component": "ak-stage-dummy"}, content_type="application/json" 339 ) 340 challenge = self.client.get(executor_url).json() 341 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 342 authorize_events = Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION) 343 self.assertEqual(authorize_events.count(), 1) 344 345 response = self.client.post( 346 executor_url, {"component": "ak-stage-autosubmit"}, content_type="application/json" 347 ) 348 349 self.assertEqual(response.status_code, 400) 350 self.assertEqual(authorize_events.count(), 1) 351 self.assertEqual(SAMLSession.objects.filter(provider=self.provider).count(), 1) 352 353 def test_direct_post_response_keeps_other_tab_plan(self): 354 """A direct SAML response in one tab leaves the flow another tab is running intact.""" 355 self.provider.sp_binding = SAMLBindings.POST 356 self.provider.save() 357 FlowStageBinding.objects.create( 358 target=self.provider.authorization_flow, 359 stage=DummyStage.objects.create(name=generate_id()), 360 order=0, 361 ) 362 direct_provider = SAMLProvider.objects.create( 363 name=generate_id(), 364 authorization_flow=create_test_flow(), 365 acs_url=self.provider.acs_url, 366 sp_binding=SAMLBindings.POST, 367 signing_kp=self.cert, 368 verification_kp=self.cert, 369 ) 370 direct_provider.property_mappings.set(SAMLPropertyMapping.objects.all()) 371 Application.objects.create(name="direct-app", slug="direct-app", provider=direct_provider) 372 self.client.force_login(create_test_admin_user()) 373 374 # Tab A starts an authorization flow and stops at its first stage. 375 self.post_authn_request(relay_state="tab_a") 376 executor_url = self.executor_url(self.provider) 377 executor_query = {"query": "next=%2Ftab-a%2F"} 378 self.assertEqual( 379 self.client.get(executor_url, executor_query).json()["component"], "ak-stage-dummy" 380 ) 381 tab_a_plan = self.client.session[SESSION_KEY_PLAN] 382 tab_a_get = self.client.session[SESSION_KEY_GET] 383 384 # Tab B signs into an application with an empty authorization flow. 385 response = self.post_authn_request("direct-app", relay_state="tab_b") 386 self.assertTemplateUsed(response, "if/saml_form_post.html") 387 self.assertEqual(response.context_data["attrs"]["RelayState"], "tab_b") 388 self.assertTrue(SAMLSession.objects.filter(provider=direct_provider).exists()) 389 self.assertEqual(self.client.session[SESSION_KEY_PLAN].flow_pk, tab_a_plan.flow_pk) 390 self.assertEqual( 391 self.client.session[SESSION_KEY_PLAN].context[PLAN_CONTEXT_APPLICATION].slug, 392 "test-app", 393 ) 394 self.assertEqual(self.client.session[SESSION_KEY_GET], tab_a_get) 395 396 # Tab A finishes with its own request. 397 self.client.post( 398 executor_url, 399 {"component": "ak-stage-dummy"}, 400 content_type="application/json", 401 query_params=executor_query, 402 ) 403 challenge = self.client.get(executor_url, executor_query).json() 404 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 405 self.assertEqual(challenge["url"], self.provider.acs_url) 406 self.assertEqual(challenge["attrs"]["RelayState"], "tab_a") 407 408 def test_signed_valid(self): 409 """Test generated AuthNRequest with valid signature""" 410 http_request = self.request_factory.get("/") 411 412 # First create an AuthNRequest 413 request_proc = RequestProcessor(self.source, http_request, "test_state") 414 auth_n = request_proc.get_auth_n() 415 self.assertEqual(auth_n.attrib["ProtocolBinding"], SAML_BINDING_POST) 416 417 request = request_proc.build_auth_n() 418 # Now we check the ID and signature 419 parsed_request = AuthNRequestParser(self.provider).parse( 420 b64encode(request.encode()).decode(), "test_state" 421 ) 422 self.assertEqual(parsed_request.id, request_proc.request_id) 423 self.assertEqual(parsed_request.relay_state, "test_state") 424 425 def test_redirect_binding_flow_redirect_includes_resume_url(self): 426 """Test SP-initiated Redirect binding keeps the original SAML URL as next.""" 427 app = Application.objects.get(slug="test-app") 428 FlowStageBinding.objects.create( 429 target=self.provider.authorization_flow, 430 stage=DummyStage.objects.create(name=generate_id()), 431 order=0, 432 ) 433 http_request = self.request_factory.get("/") 434 params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() 435 self.client.force_login(create_test_admin_user()) 436 url = reverse( 437 "authentik_providers_saml:sso-redirect", 438 kwargs={"application_slug": app.slug}, 439 ) 440 441 response = self.client.get(url, params) 442 443 self.assertEqual(response.status_code, 302) 444 redirect_query = parse_qs(urlparse(response["Location"]).query) 445 self.assertIn("next", redirect_query) 446 447 next_url = urlparse(redirect_query["next"][0]) 448 self.assertEqual(next_url.path, url) 449 next_query = parse_qs(next_url.query) 450 for key, value in params.items(): 451 self.assertEqual(next_query[key], [value]) 452 453 @patch_flag(ContinuousLogin, True) 454 def test_redirect_binding_continuous_login_final_redirect(self): 455 """Test SP-initiated Redirect binding returns a final redirect challenge under 456 continuous login, instead of an un-validated-serializer error.""" 457 self.provider.sp_binding = SAMLBindings.REDIRECT 458 self.provider.save() 459 FlowStageBinding.objects.create( 460 target=self.provider.authorization_flow, 461 stage=DummyStage.objects.create(name=generate_id()), 462 order=0, 463 ) 464 app = Application.objects.get(slug="test-app") 465 http_request = self.request_factory.get("/") 466 params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() 467 self.client.force_login(create_test_admin_user()) 468 469 # Initiate the SP-initiated request, which plans the flow and redirects into the executor. 470 initiate = self.client.get( 471 reverse( 472 "authentik_providers_saml:sso-redirect", 473 kwargs={"application_slug": app.slug}, 474 ), 475 params, 476 ) 477 self.assertEqual(initiate.status_code, 302) 478 479 # Drive the flow executor to completion, reaching SAMLFlowFinalView. 480 executor_url = reverse( 481 "authentik_api:flow-executor", 482 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 483 ) 484 challenge = self.client.get(executor_url) 485 self.assertEqual(challenge.json()["component"], "ak-stage-dummy") 486 advance = self.client.post( 487 executor_url, 488 {"component": "ak-stage-dummy"}, 489 content_type="application/json", 490 ) 491 self.assertEqual(advance.status_code, 302) 492 response = self.client.get(executor_url) 493 494 self.assertEqual(response.status_code, 200) 495 body = loads(response.content.decode()) 496 self.assertEqual(body["component"], "xak-flow-redirect") 497 self.assertTrue(body["final_redirect"]) 498 self.assertNotIn("continuous_login_hold", body) 499 self.assertTrue(body["to"].startswith(self.provider.acs_url)) 500 501 def test_request_encrypt(self): 502 """Test full SAML Request/Response flow, fully encrypted, for each supported algorithm""" 503 self.source.encryption_kp = self.cert 504 self.source.save() 505 for algorithm in (AES128_CBC, AES256_CBC, AES128_GCM, AES256_GCM): 506 with self.subTest(algorithm=algorithm): 507 self.provider.encryption_kp = self.cert 508 self.provider.encryption_algorithm = algorithm 509 self.provider.save() 510 http_request = self.request_factory.get("/", user=get_anonymous_user()) 511 512 # First create an AuthNRequest 513 request_proc = RequestProcessor(self.source, http_request, "test_state") 514 request = request_proc.build_auth_n() 515 516 # To get an assertion we need a parsed request (parsed by provider) 517 parsed_request = AuthNRequestParser(self.provider).parse( 518 b64encode(request.encode()).decode(), "test_state" 519 ) 520 # Now create a response and convert it to string (provider) 521 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 522 response = response_proc.build_response() 523 524 # The chosen algorithm must be the one advertised on the wire 525 response_xml = lxml_from_string(response.encode()) 526 self.assertEqual( 527 response_xml.xpath( 528 "//xenc:EncryptedData/xenc:EncryptionMethod/@Algorithm", 529 namespaces=NS_MAP, 530 ), 531 [algorithm], 532 ) 533 534 # Now parse the response (source), which decrypts the assertion 535 http_request.POST = QueryDict(mutable=True) 536 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 537 538 response_parser = ResponseProcessor(self.source, http_request) 539 response_parser.parse() 540 541 def test_request_encrypt_cert_only(self): 542 """Test SAML encryption with certificate-only keypair (no private key). 543 544 This tests the scenario where the IdP (provider) only has the SP's public 545 certificate for encryption, without a private key. This is the expected 546 real-world scenario since the SP would never share their private key. 547 """ 548 # Create a full keypair for the source (SP) - it needs the private key to decrypt 549 full_keypair = create_test_cert() 550 551 # Create a certificate-only keypair for the provider (IdP) 552 # This simulates having only the SP's public certificate 553 cert_only = CertificateKeyPair.objects.create( 554 name=generate_id(), 555 certificate_data=full_keypair.certificate_data, 556 key_data="", # No private key 557 ) 558 559 self.provider.encryption_kp = cert_only 560 self.provider.save() 561 self.source.encryption_kp = full_keypair 562 self.source.save() 563 http_request = self.request_factory.get("/", user=get_anonymous_user()) 564 565 # First create an AuthNRequest 566 request_proc = RequestProcessor(self.source, http_request, "test_state") 567 request = request_proc.build_auth_n() 568 569 # To get an assertion we need a parsed request (parsed by provider) 570 parsed_request = AuthNRequestParser(self.provider).parse( 571 b64encode(request.encode()).decode(), "test_state" 572 ) 573 # Now create a response and convert it to string (provider) 574 # This should work with only the certificate (public key) for encryption 575 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 576 response = response_proc.build_response() 577 578 # Now parse the response (source) - decryption requires the private key 579 http_request.POST = QueryDict(mutable=True) 580 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 581 582 response_parser = ResponseProcessor(self.source, http_request) 583 response_parser.parse() 584 585 def test_request_sign_response_and_encrypt(self): 586 """Test SAML with sign_response enabled AND encryption. 587 588 This tests the fix for signature invalidation when encryption is enabled. 589 The response must be signed AFTER encryption, not before, because encryption 590 replaces the Assertion with EncryptedAssertion which changes the response content. 591 """ 592 self.provider.sign_response = True 593 self.provider.sign_assertion = False 594 self.provider.encryption_kp = self.cert 595 self.provider.save() 596 self.source.encryption_kp = self.cert 597 self.source.signed_response = True 598 self.source.signed_assertion = False # Only response is signed, not assertion 599 self.source.save() 600 http_request = self.request_factory.get("/", user=get_anonymous_user()) 601 602 # First create an AuthNRequest 603 request_proc = RequestProcessor(self.source, http_request, "test_state") 604 request = request_proc.build_auth_n() 605 606 # To get an assertion we need a parsed request (parsed by provider) 607 parsed_request = AuthNRequestParser(self.provider).parse( 608 b64encode(request.encode()).decode(), "test_state" 609 ) 610 # Now create a response and convert it to string (provider) 611 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 612 response = response_proc.build_response() 613 614 # Verify the response contains EncryptedAssertion and a signature 615 response_xml = fromstring(response) 616 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 617 self.assertEqual( 618 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 619 ) 620 621 # Now parse the response (source) - this will verify the signature and decrypt 622 http_request.POST = QueryDict(mutable=True) 623 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 624 625 response_parser = ResponseProcessor(self.source, http_request) 626 response_parser.parse() 627 628 def test_request_sign_assertion_and_encrypt(self): 629 """Test SAML with sign_assertion enabled AND encryption. 630 631 The assertion signature should be inside the encrypted content and 632 remain valid after decryption. 633 """ 634 self.provider.sign_response = False 635 self.provider.sign_assertion = True 636 self.provider.encryption_kp = self.cert 637 self.provider.save() 638 self.source.encryption_kp = self.cert 639 self.source.signed_assertion = True 640 self.source.save() 641 http_request = self.request_factory.get("/", user=get_anonymous_user()) 642 643 # First create an AuthNRequest 644 request_proc = RequestProcessor(self.source, http_request, "test_state") 645 request = request_proc.build_auth_n() 646 647 # To get an assertion we need a parsed request (parsed by provider) 648 parsed_request = AuthNRequestParser(self.provider).parse( 649 b64encode(request.encode()).decode(), "test_state" 650 ) 651 # Now create a response and convert it to string (provider) 652 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 653 response = response_proc.build_response() 654 655 # Verify the response contains EncryptedAssertion 656 response_xml = fromstring(response) 657 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 658 659 # Now parse the response (source) - this will decrypt and verify assertion signature 660 http_request.POST = QueryDict(mutable=True) 661 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 662 663 response_parser = ResponseProcessor(self.source, http_request) 664 response_parser.parse() 665 666 def test_request_sign_both_and_encrypt(self): 667 """Test SAML with both sign_assertion and sign_response enabled AND encryption. 668 669 This is the most complex scenario: assertion is signed, then encrypted, 670 then the response is signed. Both signatures should be valid. 671 """ 672 self.provider.sign_response = True 673 self.provider.sign_assertion = True 674 self.provider.encryption_kp = self.cert 675 self.provider.save() 676 self.source.encryption_kp = self.cert 677 self.source.signed_assertion = True 678 self.source.signed_response = True 679 self.source.save() 680 http_request = self.request_factory.get("/", user=get_anonymous_user()) 681 682 # First create an AuthNRequest 683 request_proc = RequestProcessor(self.source, http_request, "test_state") 684 request = request_proc.build_auth_n() 685 686 # To get an assertion we need a parsed request (parsed by provider) 687 parsed_request = AuthNRequestParser(self.provider).parse( 688 b64encode(request.encode()).decode(), "test_state" 689 ) 690 # Now create a response and convert it to string (provider) 691 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 692 response = response_proc.build_response() 693 694 # Verify the response contains EncryptedAssertion and response signature 695 response_xml = fromstring(response) 696 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 697 self.assertEqual( 698 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 699 ) 700 701 # Now parse the response (source) - this will verify response signature, 702 # decrypt, then verify assertion signature 703 http_request.POST = QueryDict(mutable=True) 704 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 705 706 response_parser = ResponseProcessor(self.source, http_request) 707 response_parser.parse() 708 709 def test_encrypted_assertion_namespace_preservation(self): 710 """Test that encrypted assertions include namespace declarations. 711 712 When an assertion is encrypted, the resulting decrypted XML must include 713 the necessary namespace declarations (xmlns:saml) since it's now a standalone 714 document fragment, no longer inheriting namespaces from the parent Response. 715 """ 716 self.provider.encryption_kp = self.cert 717 self.provider.save() 718 self.source.encryption_kp = self.cert 719 self.source.save() 720 http_request = self.request_factory.get("/", user=get_anonymous_user()) 721 722 # First create an AuthNRequest 723 request_proc = RequestProcessor(self.source, http_request, "test_state") 724 request = request_proc.build_auth_n() 725 726 # To get an assertion we need a parsed request (parsed by provider) 727 parsed_request = AuthNRequestParser(self.provider).parse( 728 b64encode(request.encode()).decode(), "test_state" 729 ) 730 # Now create a response and convert it to string (provider) 731 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 732 response = response_proc.build_response() 733 734 # Parse the encrypted response 735 response_xml = fromstring(response) 736 encrypted_assertion = response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)[0] 737 encrypted_data = encrypted_assertion.xpath("//xenc:EncryptedData", namespaces=NS_MAP)[0] 738 739 # Decrypt the assertion manually to verify namespace is present 740 import xmlsec 741 742 manager = xmlsec.KeysManager() 743 key = xmlsec.Key.from_memory(self.cert.key_data, xmlsec.constants.KeyDataFormatPem, None) 744 manager.add_key(key) 745 enc_ctx = xmlsec.EncryptionContext(manager) 746 decrypted = enc_ctx.decrypt(encrypted_data) 747 748 # The decrypted assertion should have xmlns:saml namespace declaration 749 decrypted_str = etree.tostring(decrypted).decode() 750 self.assertIn("xmlns:saml", decrypted_str) 751 752 # Also verify full round-trip works (source can parse it) 753 http_request.POST = QueryDict(mutable=True) 754 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 755 756 response_parser = ResponseProcessor(self.source, http_request) 757 response_parser.parse() 758 759 def test_encrypted_response_schema_validation(self): 760 """Test that encrypted SAML responses validate against the SAML schema. 761 762 The response with EncryptedAssertion must be valid per saml-schema-protocol-2.0.xsd. 763 This ensures we don't have invalid elements like EncryptedData inside Assertion. 764 """ 765 self.provider.encryption_kp = self.cert 766 self.provider.save() 767 http_request = self.request_factory.get("/", user=get_anonymous_user()) 768 769 # First create an AuthNRequest 770 request_proc = RequestProcessor(self.source, http_request, "test_state") 771 request = request_proc.build_auth_n() 772 773 # To get an assertion we need a parsed request (parsed by provider) 774 parsed_request = AuthNRequestParser(self.provider).parse( 775 b64encode(request.encode()).decode(), "test_state" 776 ) 777 # Now create a response and convert it to string (provider) 778 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 779 response = response_proc.build_response() 780 781 # Validate against SAML schema 782 schema = etree.XMLSchema( 783 etree.parse("schemas/saml-schema-protocol-2.0.xsd", parser=etree.XMLParser()) # nosec 784 ) 785 self.assertTrue(schema.validate(lxml_from_string(response))) 786 787 # Verify structure: should have EncryptedAssertion, not Assertion with EncryptedData inside 788 response_xml = fromstring(response) 789 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 790 self.assertEqual(len(response_xml.xpath("//saml:Assertion", namespaces=NS_MAP)), 0) 791 792 def test_request_signed(self): 793 """Test full SAML Request/Response flow, fully signed""" 794 http_request = self.request_factory.get("/", user=get_anonymous_user()) 795 796 # First create an AuthNRequest 797 request_proc = RequestProcessor(self.source, http_request, "test_state") 798 request = request_proc.build_auth_n() 799 800 # To get an assertion we need a parsed request (parsed by provider) 801 parsed_request = AuthNRequestParser(self.provider).parse( 802 b64encode(request.encode()).decode(), "test_state" 803 ) 804 # Now create a response and convert it to string (provider) 805 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 806 response = response_proc.build_response() 807 808 # Now parse the response (source) 809 http_request.POST = QueryDict(mutable=True) 810 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 811 812 response_parser = ResponseProcessor(self.source, http_request) 813 response_parser.parse() 814 815 def test_request_signed_both(self): 816 """Test full SAML Request/Response flow, fully signed""" 817 self.provider.sign_assertion = True 818 self.provider.sign_response = True 819 self.provider.save() 820 self.source.signed_response = True 821 http_request = self.request_factory.get("/", user=get_anonymous_user()) 822 823 # First create an AuthNRequest 824 request_proc = RequestProcessor(self.source, http_request, "test_state") 825 request = request_proc.build_auth_n() 826 827 # To get an assertion we need a parsed request (parsed by provider) 828 parsed_request = AuthNRequestParser(self.provider).parse( 829 b64encode(request.encode()).decode(), "test_state" 830 ) 831 # Now create a response and convert it to string (provider) 832 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 833 response = response_proc.build_response() 834 # Ensure both response and assertion ID are in the response twice (once as ID attribute, 835 # once as ds:Reference URI) 836 self.assertEqual(response.count(response_proc._assertion_id), 2) 837 self.assertEqual(response.count(response_proc._response_id), 2) 838 839 schema = etree.XMLSchema( 840 etree.parse("schemas/saml-schema-protocol-2.0.xsd", parser=etree.XMLParser()) # nosec 841 ) 842 self.assertTrue(schema.validate(lxml_from_string(response))) 843 844 response_xml = fromstring(response) 845 self.assertEqual( 846 len(response_xml.xpath("//saml:Assertion/ds:Signature", namespaces=NS_MAP)), 1 847 ) 848 self.assertEqual( 849 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 850 ) 851 852 # Now parse the response (source) 853 http_request.POST = QueryDict(mutable=True) 854 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 855 856 response_parser = ResponseProcessor(self.source, http_request) 857 response_parser.parse() 858 859 def test_request_id_invalid(self): 860 """Test generated AuthNRequest with invalid request ID""" 861 http_request = self.request_factory.get("/", user=get_anonymous_user()) 862 863 # First create an AuthNRequest 864 request_proc = RequestProcessor(self.source, http_request, "test_state") 865 request = request_proc.build_auth_n() 866 867 # change the request ID 868 http_request.session[SESSION_KEY_REQUEST_ID] = "test" 869 http_request.session.save() 870 871 # To get an assertion we need a parsed request (parsed by provider) 872 parsed_request = AuthNRequestParser(self.provider).parse( 873 b64encode(request.encode()).decode(), "test_state" 874 ) 875 # Now create a response and convert it to string (provider) 876 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 877 response = response_proc.build_response() 878 879 # Now parse the response (source) 880 http_request.POST = QueryDict(mutable=True) 881 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 882 883 response_parser = ResponseProcessor(self.source, http_request) 884 885 with self.assertRaises(MismatchedRequestID): 886 response_parser.parse() 887 888 def test_signed_valid_detached(self): 889 """Test generated AuthNRequest with valid signature (detached)""" 890 http_request = self.request_factory.get("/") 891 892 # First create an AuthNRequest 893 request_proc = RequestProcessor(self.source, http_request, "test_state") 894 params = request_proc.build_auth_n_detached() 895 # Now we check the ID and signature 896 parsed_request = AuthNRequestParser(self.provider).parse_detached( 897 params["SAMLRequest"], 898 params["RelayState"], 899 params["Signature"], 900 params["SigAlg"], 901 ) 902 self.assertEqual(parsed_request.id, request_proc.request_id) 903 self.assertEqual(parsed_request.relay_state, "test_state") 904 905 def test_signed_detached_static(self): 906 """Test request with detached signature, 907 taken from https://www.samltool.com/generic_sso_req.php""" 908 static_keypair = CertificateKeyPair.objects.create( 909 name="samltool", certificate_data=REDIRECT_CERT 910 ) 911 provider = SAMLProvider( 912 name="samltool", 913 authorization_flow=create_test_flow(), 914 acs_url="https://10.120.20.200/saml-sp/SAML2/POST", 915 audience="https://10.120.20.200/saml-sp/SAML2/POST", 916 issuer_override="https://10.120.20.200/saml-sp/SAML2/POST", 917 signing_kp=static_keypair, 918 verification_kp=static_keypair, 919 ) 920 parsed_request = AuthNRequestParser(provider).parse_detached( 921 REDIRECT_REQUEST, REDIRECT_RELAY_STATE, REDIRECT_SIGNATURE, REDIRECT_SIG_ALG 922 ) 923 self.assertEqual(parsed_request.id, "_dcf55fcd27a887e60a7ef9ee6fd3adab") 924 self.assertEqual(parsed_request.name_id_policy, SAML_NAME_ID_FORMAT_UNSPECIFIED) 925 self.assertEqual(parsed_request.relay_state, REDIRECT_RELAY_STATE) 926 927 def test_signed_static(self): 928 """Test post request with static request""" 929 provider = SAMLProvider( 930 name="aws", 931 authorization_flow=create_test_flow(), 932 acs_url=( 933 "https://eu-central-1.signin.aws.amazon.com/platform/" 934 "saml/acs/2d737f96-55fb-4035-953e-5e24134eb778" 935 ), 936 audience="https://10.120.20.200/saml-sp/SAML2/POST", 937 issuer_override="https://10.120.20.200/saml-sp/SAML2/POST", 938 signing_kp=create_test_cert(), 939 ) 940 parsed_request = AuthNRequestParser(provider).parse(POST_REQUEST) 941 self.assertEqual(parsed_request.id, "aws_LDxLGeubpc5lx12gxCgS6uPbix1yd5re") 942 self.assertEqual(parsed_request.name_id_policy, SAML_NAME_ID_FORMAT_EMAIL) 943 944 def test_authn_context_class_ref_mapping(self): 945 """Test custom authn_context_class_ref""" 946 authn_context_class_ref = generate_id() 947 mapping = SAMLPropertyMapping.objects.create( 948 name=generate_id(), expression=f"""return '{authn_context_class_ref}'""" 949 ) 950 self.provider.authn_context_class_ref_mapping = mapping 951 self.provider.save() 952 user = create_test_admin_user() 953 http_request = self.request_factory.get("/", user=user) 954 955 # First create an AuthNRequest 956 request_proc = RequestProcessor(self.source, http_request, "test_state") 957 request = request_proc.build_auth_n() 958 959 # To get an assertion we need a parsed request (parsed by provider) 960 parsed_request = AuthNRequestParser(self.provider).parse( 961 b64encode(request.encode()).decode(), "test_state" 962 ) 963 # Now create a response and convert it to string (provider) 964 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 965 response = response_proc.build_response() 966 self.assertIn(user.username, response) 967 self.assertIn(authn_context_class_ref, response) 968 969 def test_authn_context_class_ref_mapping_invalid(self): 970 """Test custom authn_context_class_ref (invalid)""" 971 mapping = SAMLPropertyMapping.objects.create(name=generate_id(), expression="q") 972 self.provider.authn_context_class_ref_mapping = mapping 973 self.provider.save() 974 user = create_test_admin_user() 975 http_request = self.request_factory.get("/", user=user) 976 977 # First create an AuthNRequest 978 request_proc = RequestProcessor(self.source, http_request, "test_state") 979 request = request_proc.build_auth_n() 980 981 # To get an assertion we need a parsed request (parsed by provider) 982 parsed_request = AuthNRequestParser(self.provider).parse( 983 b64encode(request.encode()).decode(), "test_state" 984 ) 985 # Now create a response and convert it to string (provider) 986 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 987 response = response_proc.build_response() 988 self.assertIn(user.username, response) 989 990 events = Event.objects.filter( 991 action=EventAction.CONFIGURATION_ERROR, 992 ) 993 self.assertTrue(events.exists()) 994 self.assertEqual( 995 events.first().context["message"], 996 f"Failed to evaluate property-mapping: '{mapping.name}'", 997 ) 998 999 def test_request_attributes(self): 1000 """Test full SAML Request/Response flow, fully signed""" 1001 user = create_test_admin_user() 1002 http_request = self.request_factory.get("/", user=user) 1003 1004 # First create an AuthNRequest 1005 request_proc = RequestProcessor(self.source, http_request, "test_state") 1006 request = request_proc.build_auth_n() 1007 1008 # To get an assertion we need a parsed request (parsed by provider) 1009 parsed_request = AuthNRequestParser(self.provider).parse( 1010 b64encode(request.encode()).decode(), "test_state" 1011 ) 1012 # Now create a response and convert it to string (provider) 1013 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 1014 self.assertIn(user.username, response_proc.build_response()) 1015 1016 def test_request_attributes_invalid(self): 1017 """Test full SAML Request/Response flow, fully signed""" 1018 user = create_test_admin_user() 1019 http_request = self.request_factory.get("/", user=user) 1020 1021 # First create an AuthNRequest 1022 request_proc = RequestProcessor(self.source, http_request, "test_state") 1023 request = request_proc.build_auth_n() 1024 1025 # Create invalid PropertyMapping 1026 mapping = SAMLPropertyMapping.objects.create( 1027 name=generate_id(), saml_name="test", expression="q" 1028 ) 1029 self.provider.property_mappings.add(mapping) 1030 1031 # To get an assertion we need a parsed request (parsed by provider) 1032 parsed_request = AuthNRequestParser(self.provider).parse( 1033 b64encode(request.encode()).decode(), "test_state" 1034 ) 1035 # Now create a response and convert it to string (provider) 1036 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 1037 self.assertIn(user.username, response_proc.build_response()) 1038 1039 events = Event.objects.filter( 1040 action=EventAction.CONFIGURATION_ERROR, 1041 ) 1042 self.assertTrue(events.exists()) 1043 self.assertEqual( 1044 events.first().context["message"], 1045 f"Failed to evaluate property-mapping: '{mapping.name}'", 1046 ) 1047 1048 def test_idp_initiated(self): 1049 """Test IDP-initiated login""" 1050 self.provider.default_relay_state = generate_id() 1051 request = AuthNRequestParser(self.provider).idp_initiated() 1052 self.assertEqual(request.id, None) 1053 self.assertEqual(request.relay_state, self.provider.default_relay_state) 1054 self.assertFalse(request.force_authn) 1055 1056 def test_force_authn(self): 1057 """Test that ForceAuthn from the SP is parsed from the AuthNRequest""" 1058 self.source.force_authn = True 1059 self.source.save() 1060 http_request = self.request_factory.get("/") 1061 1062 request_proc = RequestProcessor(self.source, http_request, "test_state") 1063 request = request_proc.build_auth_n() 1064 parsed_request = AuthNRequestParser(self.provider).parse( 1065 b64encode(request.encode()).decode(), "test_state" 1066 ) 1067 self.assertTrue(parsed_request.force_authn) 1068 1069 def _sso_redirect_with_force_authn(self): 1070 """Send an SP-initiated Redirect binding AuthnRequest with ForceAuthn="true" from a 1071 logged-in session and return the response.""" 1072 self.source.force_authn = True 1073 self.source.save() 1074 self.provider.authentication_flow = create_test_flow() 1075 self.provider.save() 1076 for flow in (self.provider.authorization_flow, self.provider.authentication_flow): 1077 FlowStageBinding.objects.create( 1078 target=flow, 1079 stage=DummyStage.objects.create(name=generate_id()), 1080 order=0, 1081 ) 1082 http_request = self.request_factory.get("/") 1083 params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() 1084 self.client.force_login(create_test_admin_user()) 1085 return self.client.get( 1086 reverse( 1087 "authentik_providers_saml:sso-redirect", 1088 kwargs={"application_slug": "test-app"}, 1089 ), 1090 params, 1091 ) 1092 1093 def test_force_authn_honored(self): 1094 """Test that ForceAuthn triggers re-authentication by default""" 1095 response = self._sso_redirect_with_force_authn() 1096 1097 self.assertEqual(response.status_code, 302) 1098 self.assertIn(self.provider.authentication_flow.slug, response["Location"]) 1099 self.assertIn(SESSION_KEY_LAST_LOGIN_UID, self.client.session) 1100 1101 def test_force_authn_ignored(self): 1102 """Test that ForceAuthn is ignored when the provider is configured to do so""" 1103 self.provider.ignore_force_authn = True 1104 self.provider.save() 1105 response = self._sso_redirect_with_force_authn() 1106 1107 self.assertEqual(response.status_code, 302) 1108 self.assertIn(self.provider.authorization_flow.slug, response["Location"]) 1109 self.assertNotIn(self.provider.authentication_flow.slug, response["Location"]) 1110 self.assertNotIn(SESSION_KEY_LAST_LOGIN_UID, self.client.session) 1111 1112 def test_doctype(self): 1113 """Test that a request with a document type declaration is refused""" 1114 request = ( 1115 '<?xml version="1.0"?>' 1116 "<!DOCTYPE samlp:AuthnRequest>" 1117 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1118 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1119 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1120 ) 1121 1122 with self.assertRaises(CannotHandleAssertion) as ctx: 1123 AuthNRequestParser(self.provider).parse(b64encode(request.encode()).decode()) 1124 # The user-facing message is generic; the parser's reason only goes to the detail 1125 self.assertEqual(str(ctx.exception), str(ERROR_CANNOT_DECODE_REQUEST)) 1126 self.assertIn("XML document contains a DOCTYPE declaration", str(ctx.exception.detail)) 1127 1128 def test_invalid_base64(self): 1129 """Test that a SAMLRequest that is not valid base64 is rejected, not a server error""" 1130 for parse in ( 1131 lambda: AuthNRequestParser(self.provider).parse("%%%not-base64%%%"), 1132 lambda: AuthNRequestParser(self.provider).parse_detached("%%%not-base64%%%", None), 1133 ): 1134 with self.assertRaises(CannotHandleAssertion) as ctx: 1135 parse() 1136 self.assertEqual(str(ctx.exception), str(ERROR_CANNOT_DECODE_REQUEST)) 1137 self.assertIn("base64", str(ctx.exception.detail)) 1138 1139 def test_acs_url_mismatch(self): 1140 """Test that a mismatched ACS URL is rejected without echoing either URL to the user""" 1141 # Unsigned request, so the ACS check is reached instead of the signature check 1142 self.provider.verification_kp = None 1143 self.provider.save() 1144 request = ( 1145 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1146 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1147 'AssertionConsumerServiceURL="https://evil.example.com/acs"/>' 1148 ) 1149 1150 with self.assertRaises(CannotHandleAssertion) as ctx: 1151 AuthNRequestParser(self.provider).parse(b64encode(request.encode()).decode()) 1152 self.assertEqual(str(ctx.exception), str(ERROR_ACS_URL_MISMATCH)) 1153 self.assertNotIn("evil.example.com", str(ctx.exception)) 1154 self.assertIn("https://evil.example.com/acs", ctx.exception.detail) 1155 self.assertIn(self.provider.acs_url, ctx.exception.detail) 1156 1157 def test_malformed_unsigned(self): 1158 """Test that malformed requests to a provider without a verification certificate are 1159 rejected with a handled error instead of a server error""" 1160 self.provider.verification_kp = None 1161 self.provider.save() 1162 missing_id = ( 1163 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1164 'Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1165 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1166 ) 1167 parser = AuthNRequestParser(self.provider) 1168 for payload in ("this is not xml", missing_id): 1169 with self.subTest(payload=payload, binding="post"): 1170 with self.assertRaisesMessage( 1171 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1172 ): 1173 parser.parse(b64encode(payload.encode()).decode()) 1174 with self.subTest(payload=payload, binding="redirect"): 1175 with self.assertRaisesMessage( 1176 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1177 ): 1178 parser.parse_detached(deflate_and_base64_encode(payload), None) 1179 1180 for binding, method in (("post", parser.parse), ("redirect", parser.parse_detached)): 1181 with self.subTest(payload="not base64", binding=binding): 1182 with self.assertRaisesMessage( 1183 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1184 ): 1185 method("%%%not-base64%%%", None) 1186 1187 def test_redirect_over_size_limit(self): 1188 """Test that a redirect-binding request that inflates beyond the size limit is refused""" 1189 request = deflate_and_base64_encode( 1190 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1191 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1192 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1193 + " " * (32 * 1024 * 1024) 1194 ) 1195 1196 tracemalloc.start() 1197 self.addCleanup(tracemalloc.stop) 1198 with self.assertRaises(CannotHandleAssertion): 1199 AuthNRequestParser(self.provider).parse_detached(request, None) 1200 _, peak = tracemalloc.get_traced_memory() 1201 1202 self.assertLess(peak, 32 * 1024 * 1024)
117class TestAuthNRequest(TestCase): 118 """Test AuthN Request generator and parser""" 119 120 @apply_blueprint("system/providers-saml.yaml") 121 def setUp(self): 122 self.request_factory = RequestFactory() 123 self.cert = create_test_cert() 124 self.provider: SAMLProvider = SAMLProvider.objects.create( 125 authorization_flow=create_test_flow(), 126 acs_url="http://testserver/source/saml/provider/acs/", 127 signing_kp=self.cert, 128 verification_kp=self.cert, 129 ) 130 self.provider.property_mappings.set(SAMLPropertyMapping.objects.all()) 131 self.provider.save() 132 Application.objects.create( 133 name="test-app", 134 slug="test-app", 135 provider=self.provider, 136 ) 137 self.source = SAMLSource.objects.create( 138 slug="provider", 139 issuer_override="authentik", 140 pre_authentication_flow=create_test_flow(), 141 signing_kp=self.cert, 142 verification_kp=self.cert, 143 signed_assertion=True, 144 binding_type=SAMLBindingTypes.POST, 145 ) 146 147 def post_authn_request(self, application_slug: str = "test-app", relay_state="test_state"): 148 """Send an SP-initiated AuthnRequest using the HTTP-POST binding.""" 149 request = RequestProcessor( 150 self.source, self.request_factory.get("/"), relay_state 151 ).build_auth_n() 152 return self.client.post( 153 reverse( 154 "authentik_providers_saml:sso-post", 155 kwargs={"application_slug": application_slug}, 156 ), 157 { 158 "SAMLRequest": b64encode(request.encode()).decode(), 159 "RelayState": relay_state, 160 }, 161 ) 162 163 def bind_excluded_consent_stage(self): 164 """Bind a consent stage to the authorization flow whose policy excludes every user 165 while the flow is planned.""" 166 binding = FlowStageBinding.objects.create( 167 target=self.provider.authorization_flow, 168 stage=ConsentStage.objects.create(name=generate_id()), 169 order=0, 170 evaluate_on_plan=True, 171 re_evaluate_policies=False, 172 ) 173 PolicyBinding.objects.create( 174 target=binding, 175 policy=DummyPolicy.objects.create( 176 name=generate_id(), result=False, wait_min=0, wait_max=1 177 ), 178 order=0, 179 ) 180 181 def executor_url(self, provider: SAMLProvider) -> str: 182 """Flow executor API URL for a provider's authorization flow.""" 183 return reverse( 184 "authentik_api:flow-executor", 185 kwargs={"flow_slug": provider.authorization_flow.slug}, 186 ) 187 188 def assert_direct_post_response(self, response): 189 """Assert a direct SAML HTTP-POST response and its side effects.""" 190 self.assertEqual(response.status_code, 200) 191 self.assertTemplateUsed(response, "if/saml_form_post.html") 192 self.assertEqual(response.context_data["redirect_uri"], self.provider.acs_url) 193 self.assertEqual(response.context_data["attrs"]["RelayState"], "test_state") 194 self.assertIn("SAMLResponse", response.context_data["attrs"]) 195 self.assertIn("no-store", response["Cache-Control"]) 196 self.assertEqual(response["Pragma"], "no-cache") 197 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 198 self.assertTrue(SAMLSession.objects.filter(provider=self.provider).exists()) 199 self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) 200 201 def test_post_response_empty_flow_is_direct(self): 202 """An empty authorization flow returns the SAML POST form directly.""" 203 self.provider.sp_binding = SAMLBindings.POST 204 self.provider.save() 205 self.client.force_login(create_test_admin_user()) 206 207 self.assert_direct_post_response(self.post_authn_request()) 208 209 def test_post_response_empty_flow_error_is_error_page(self): 210 """A direct SAML error renders an HTML error without exposing internal details.""" 211 self.provider.sp_binding = SAMLBindings.POST 212 self.provider.save() 213 self.client.force_login(create_test_admin_user()) 214 215 with patch.object( 216 AssertionProcessor, "build_response", side_effect=SAMLException("internal test error") 217 ): 218 response = self.post_authn_request() 219 220 self.assertEqual(response.status_code, 400) 221 self.assertTemplateUsed(response, "if/error.html") 222 self.assertContains(response, "Failed to process SAML assertion.", status_code=400) 223 self.assertNotContains(response, "internal test error", status_code=400) 224 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 225 self.assertFalse(SAMLSession.objects.filter(provider=self.provider).exists()) 226 self.assertTrue(Event.objects.filter(action=EventAction.CONFIGURATION_ERROR).exists()) 227 228 @patch_flag(ContinuousLogin, True) 229 def test_post_response_empty_flow_is_direct_with_continuous_login(self): 230 """Continuous login does not force an empty authorization flow into the executor.""" 231 self.provider.sp_binding = SAMLBindings.POST 232 self.provider.save() 233 self.client.force_login(create_test_admin_user()) 234 235 self.assert_direct_post_response(self.post_authn_request()) 236 237 @patch_flag(ContinuousLogin, True) 238 def test_redirect_response_empty_flow_is_direct_with_continuous_login(self): 239 """An empty authorization flow returns the SAML Redirect response directly.""" 240 self.provider.sp_binding = SAMLBindings.REDIRECT 241 self.provider.save() 242 app = Application.objects.get(slug="test-app") 243 params = RequestProcessor( 244 self.source, self.request_factory.get("/"), "test_state" 245 ).build_auth_n_detached() 246 self.client.force_login(create_test_admin_user()) 247 248 response = self.client.get( 249 reverse( 250 "authentik_providers_saml:sso-redirect", 251 kwargs={"application_slug": app.slug}, 252 ), 253 params, 254 ) 255 256 self.assertEqual(response.status_code, 302) 257 redirect = urlparse(response["Location"]) 258 self.assertEqual( 259 f"{redirect.scheme}://{redirect.netloc}{redirect.path}", self.provider.acs_url 260 ) 261 redirect_query = parse_qs(redirect.query) 262 self.assertEqual(redirect_query["RelayState"], ["test_state"]) 263 self.assertIn("SAMLResponse", redirect_query) 264 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 265 self.assertTrue(SAMLSession.objects.filter(provider=self.provider).exists()) 266 self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) 267 268 def test_post_response_nonempty_flow_uses_executor(self): 269 """A configured authorization stage keeps using the flow executor.""" 270 self.provider.sp_binding = SAMLBindings.POST 271 self.provider.save() 272 FlowStageBinding.objects.create( 273 target=self.provider.authorization_flow, 274 stage=DummyStage.objects.create(name=generate_id()), 275 order=0, 276 ) 277 self.client.force_login(create_test_admin_user()) 278 279 response = self.post_authn_request() 280 281 self.assertEqual(response.status_code, 302) 282 self.assertEqual( 283 urlparse(response["Location"]).path, 284 reverse( 285 "authentik_core:if-flow", 286 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 287 ), 288 ) 289 self.assertIn(SESSION_KEY_PLAN, self.client.session) 290 291 def test_post_response_excluded_stage_is_direct(self): 292 """A configured stage that policies exclude for this user doesn't need the executor.""" 293 self.provider.sp_binding = SAMLBindings.POST 294 self.provider.save() 295 self.bind_excluded_consent_stage() 296 self.client.force_login(create_test_admin_user()) 297 298 self.assert_direct_post_response(self.post_authn_request()) 299 300 @patch_flag(ContinuousLogin, True) 301 def test_post_response_excluded_stage_uses_executor_with_continuous_login(self): 302 """With continuous login, a configured stage keeps the response in the flow executor 303 even when policies exclude it, since other tabs were told to wait for this flow.""" 304 self.provider.sp_binding = SAMLBindings.POST 305 self.provider.save() 306 self.bind_excluded_consent_stage() 307 self.client.force_login(create_test_admin_user()) 308 309 response = self.post_authn_request() 310 311 self.assertEqual(response.status_code, 302) 312 self.assertEqual( 313 urlparse(response["Location"]).path, 314 reverse( 315 "authentik_core:if-flow", 316 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 317 ), 318 ) 319 self.assertFalse(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) 320 challenge = self.client.get(self.executor_url(self.provider)).json() 321 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 322 self.assertEqual(challenge["url"], self.provider.acs_url) 323 324 def test_post_to_executor_final_stage_does_not_reissue_assertion(self): 325 """A POST to the flow executor at the final stage keeps the challenge-response handling 326 instead of issuing another assertion.""" 327 self.provider.sp_binding = SAMLBindings.POST 328 self.provider.save() 329 FlowStageBinding.objects.create( 330 target=self.provider.authorization_flow, 331 stage=DummyStage.objects.create(name=generate_id()), 332 order=0, 333 ) 334 self.client.force_login(create_test_admin_user()) 335 self.post_authn_request() 336 executor_url = self.executor_url(self.provider) 337 self.client.get(executor_url) 338 self.client.post( 339 executor_url, {"component": "ak-stage-dummy"}, content_type="application/json" 340 ) 341 challenge = self.client.get(executor_url).json() 342 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 343 authorize_events = Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION) 344 self.assertEqual(authorize_events.count(), 1) 345 346 response = self.client.post( 347 executor_url, {"component": "ak-stage-autosubmit"}, content_type="application/json" 348 ) 349 350 self.assertEqual(response.status_code, 400) 351 self.assertEqual(authorize_events.count(), 1) 352 self.assertEqual(SAMLSession.objects.filter(provider=self.provider).count(), 1) 353 354 def test_direct_post_response_keeps_other_tab_plan(self): 355 """A direct SAML response in one tab leaves the flow another tab is running intact.""" 356 self.provider.sp_binding = SAMLBindings.POST 357 self.provider.save() 358 FlowStageBinding.objects.create( 359 target=self.provider.authorization_flow, 360 stage=DummyStage.objects.create(name=generate_id()), 361 order=0, 362 ) 363 direct_provider = SAMLProvider.objects.create( 364 name=generate_id(), 365 authorization_flow=create_test_flow(), 366 acs_url=self.provider.acs_url, 367 sp_binding=SAMLBindings.POST, 368 signing_kp=self.cert, 369 verification_kp=self.cert, 370 ) 371 direct_provider.property_mappings.set(SAMLPropertyMapping.objects.all()) 372 Application.objects.create(name="direct-app", slug="direct-app", provider=direct_provider) 373 self.client.force_login(create_test_admin_user()) 374 375 # Tab A starts an authorization flow and stops at its first stage. 376 self.post_authn_request(relay_state="tab_a") 377 executor_url = self.executor_url(self.provider) 378 executor_query = {"query": "next=%2Ftab-a%2F"} 379 self.assertEqual( 380 self.client.get(executor_url, executor_query).json()["component"], "ak-stage-dummy" 381 ) 382 tab_a_plan = self.client.session[SESSION_KEY_PLAN] 383 tab_a_get = self.client.session[SESSION_KEY_GET] 384 385 # Tab B signs into an application with an empty authorization flow. 386 response = self.post_authn_request("direct-app", relay_state="tab_b") 387 self.assertTemplateUsed(response, "if/saml_form_post.html") 388 self.assertEqual(response.context_data["attrs"]["RelayState"], "tab_b") 389 self.assertTrue(SAMLSession.objects.filter(provider=direct_provider).exists()) 390 self.assertEqual(self.client.session[SESSION_KEY_PLAN].flow_pk, tab_a_plan.flow_pk) 391 self.assertEqual( 392 self.client.session[SESSION_KEY_PLAN].context[PLAN_CONTEXT_APPLICATION].slug, 393 "test-app", 394 ) 395 self.assertEqual(self.client.session[SESSION_KEY_GET], tab_a_get) 396 397 # Tab A finishes with its own request. 398 self.client.post( 399 executor_url, 400 {"component": "ak-stage-dummy"}, 401 content_type="application/json", 402 query_params=executor_query, 403 ) 404 challenge = self.client.get(executor_url, executor_query).json() 405 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 406 self.assertEqual(challenge["url"], self.provider.acs_url) 407 self.assertEqual(challenge["attrs"]["RelayState"], "tab_a") 408 409 def test_signed_valid(self): 410 """Test generated AuthNRequest with valid signature""" 411 http_request = self.request_factory.get("/") 412 413 # First create an AuthNRequest 414 request_proc = RequestProcessor(self.source, http_request, "test_state") 415 auth_n = request_proc.get_auth_n() 416 self.assertEqual(auth_n.attrib["ProtocolBinding"], SAML_BINDING_POST) 417 418 request = request_proc.build_auth_n() 419 # Now we check the ID and signature 420 parsed_request = AuthNRequestParser(self.provider).parse( 421 b64encode(request.encode()).decode(), "test_state" 422 ) 423 self.assertEqual(parsed_request.id, request_proc.request_id) 424 self.assertEqual(parsed_request.relay_state, "test_state") 425 426 def test_redirect_binding_flow_redirect_includes_resume_url(self): 427 """Test SP-initiated Redirect binding keeps the original SAML URL as next.""" 428 app = Application.objects.get(slug="test-app") 429 FlowStageBinding.objects.create( 430 target=self.provider.authorization_flow, 431 stage=DummyStage.objects.create(name=generate_id()), 432 order=0, 433 ) 434 http_request = self.request_factory.get("/") 435 params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() 436 self.client.force_login(create_test_admin_user()) 437 url = reverse( 438 "authentik_providers_saml:sso-redirect", 439 kwargs={"application_slug": app.slug}, 440 ) 441 442 response = self.client.get(url, params) 443 444 self.assertEqual(response.status_code, 302) 445 redirect_query = parse_qs(urlparse(response["Location"]).query) 446 self.assertIn("next", redirect_query) 447 448 next_url = urlparse(redirect_query["next"][0]) 449 self.assertEqual(next_url.path, url) 450 next_query = parse_qs(next_url.query) 451 for key, value in params.items(): 452 self.assertEqual(next_query[key], [value]) 453 454 @patch_flag(ContinuousLogin, True) 455 def test_redirect_binding_continuous_login_final_redirect(self): 456 """Test SP-initiated Redirect binding returns a final redirect challenge under 457 continuous login, instead of an un-validated-serializer error.""" 458 self.provider.sp_binding = SAMLBindings.REDIRECT 459 self.provider.save() 460 FlowStageBinding.objects.create( 461 target=self.provider.authorization_flow, 462 stage=DummyStage.objects.create(name=generate_id()), 463 order=0, 464 ) 465 app = Application.objects.get(slug="test-app") 466 http_request = self.request_factory.get("/") 467 params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() 468 self.client.force_login(create_test_admin_user()) 469 470 # Initiate the SP-initiated request, which plans the flow and redirects into the executor. 471 initiate = self.client.get( 472 reverse( 473 "authentik_providers_saml:sso-redirect", 474 kwargs={"application_slug": app.slug}, 475 ), 476 params, 477 ) 478 self.assertEqual(initiate.status_code, 302) 479 480 # Drive the flow executor to completion, reaching SAMLFlowFinalView. 481 executor_url = reverse( 482 "authentik_api:flow-executor", 483 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 484 ) 485 challenge = self.client.get(executor_url) 486 self.assertEqual(challenge.json()["component"], "ak-stage-dummy") 487 advance = self.client.post( 488 executor_url, 489 {"component": "ak-stage-dummy"}, 490 content_type="application/json", 491 ) 492 self.assertEqual(advance.status_code, 302) 493 response = self.client.get(executor_url) 494 495 self.assertEqual(response.status_code, 200) 496 body = loads(response.content.decode()) 497 self.assertEqual(body["component"], "xak-flow-redirect") 498 self.assertTrue(body["final_redirect"]) 499 self.assertNotIn("continuous_login_hold", body) 500 self.assertTrue(body["to"].startswith(self.provider.acs_url)) 501 502 def test_request_encrypt(self): 503 """Test full SAML Request/Response flow, fully encrypted, for each supported algorithm""" 504 self.source.encryption_kp = self.cert 505 self.source.save() 506 for algorithm in (AES128_CBC, AES256_CBC, AES128_GCM, AES256_GCM): 507 with self.subTest(algorithm=algorithm): 508 self.provider.encryption_kp = self.cert 509 self.provider.encryption_algorithm = algorithm 510 self.provider.save() 511 http_request = self.request_factory.get("/", user=get_anonymous_user()) 512 513 # First create an AuthNRequest 514 request_proc = RequestProcessor(self.source, http_request, "test_state") 515 request = request_proc.build_auth_n() 516 517 # To get an assertion we need a parsed request (parsed by provider) 518 parsed_request = AuthNRequestParser(self.provider).parse( 519 b64encode(request.encode()).decode(), "test_state" 520 ) 521 # Now create a response and convert it to string (provider) 522 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 523 response = response_proc.build_response() 524 525 # The chosen algorithm must be the one advertised on the wire 526 response_xml = lxml_from_string(response.encode()) 527 self.assertEqual( 528 response_xml.xpath( 529 "//xenc:EncryptedData/xenc:EncryptionMethod/@Algorithm", 530 namespaces=NS_MAP, 531 ), 532 [algorithm], 533 ) 534 535 # Now parse the response (source), which decrypts the assertion 536 http_request.POST = QueryDict(mutable=True) 537 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 538 539 response_parser = ResponseProcessor(self.source, http_request) 540 response_parser.parse() 541 542 def test_request_encrypt_cert_only(self): 543 """Test SAML encryption with certificate-only keypair (no private key). 544 545 This tests the scenario where the IdP (provider) only has the SP's public 546 certificate for encryption, without a private key. This is the expected 547 real-world scenario since the SP would never share their private key. 548 """ 549 # Create a full keypair for the source (SP) - it needs the private key to decrypt 550 full_keypair = create_test_cert() 551 552 # Create a certificate-only keypair for the provider (IdP) 553 # This simulates having only the SP's public certificate 554 cert_only = CertificateKeyPair.objects.create( 555 name=generate_id(), 556 certificate_data=full_keypair.certificate_data, 557 key_data="", # No private key 558 ) 559 560 self.provider.encryption_kp = cert_only 561 self.provider.save() 562 self.source.encryption_kp = full_keypair 563 self.source.save() 564 http_request = self.request_factory.get("/", user=get_anonymous_user()) 565 566 # First create an AuthNRequest 567 request_proc = RequestProcessor(self.source, http_request, "test_state") 568 request = request_proc.build_auth_n() 569 570 # To get an assertion we need a parsed request (parsed by provider) 571 parsed_request = AuthNRequestParser(self.provider).parse( 572 b64encode(request.encode()).decode(), "test_state" 573 ) 574 # Now create a response and convert it to string (provider) 575 # This should work with only the certificate (public key) for encryption 576 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 577 response = response_proc.build_response() 578 579 # Now parse the response (source) - decryption requires the private key 580 http_request.POST = QueryDict(mutable=True) 581 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 582 583 response_parser = ResponseProcessor(self.source, http_request) 584 response_parser.parse() 585 586 def test_request_sign_response_and_encrypt(self): 587 """Test SAML with sign_response enabled AND encryption. 588 589 This tests the fix for signature invalidation when encryption is enabled. 590 The response must be signed AFTER encryption, not before, because encryption 591 replaces the Assertion with EncryptedAssertion which changes the response content. 592 """ 593 self.provider.sign_response = True 594 self.provider.sign_assertion = False 595 self.provider.encryption_kp = self.cert 596 self.provider.save() 597 self.source.encryption_kp = self.cert 598 self.source.signed_response = True 599 self.source.signed_assertion = False # Only response is signed, not assertion 600 self.source.save() 601 http_request = self.request_factory.get("/", user=get_anonymous_user()) 602 603 # First create an AuthNRequest 604 request_proc = RequestProcessor(self.source, http_request, "test_state") 605 request = request_proc.build_auth_n() 606 607 # To get an assertion we need a parsed request (parsed by provider) 608 parsed_request = AuthNRequestParser(self.provider).parse( 609 b64encode(request.encode()).decode(), "test_state" 610 ) 611 # Now create a response and convert it to string (provider) 612 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 613 response = response_proc.build_response() 614 615 # Verify the response contains EncryptedAssertion and a signature 616 response_xml = fromstring(response) 617 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 618 self.assertEqual( 619 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 620 ) 621 622 # Now parse the response (source) - this will verify the signature and decrypt 623 http_request.POST = QueryDict(mutable=True) 624 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 625 626 response_parser = ResponseProcessor(self.source, http_request) 627 response_parser.parse() 628 629 def test_request_sign_assertion_and_encrypt(self): 630 """Test SAML with sign_assertion enabled AND encryption. 631 632 The assertion signature should be inside the encrypted content and 633 remain valid after decryption. 634 """ 635 self.provider.sign_response = False 636 self.provider.sign_assertion = True 637 self.provider.encryption_kp = self.cert 638 self.provider.save() 639 self.source.encryption_kp = self.cert 640 self.source.signed_assertion = True 641 self.source.save() 642 http_request = self.request_factory.get("/", user=get_anonymous_user()) 643 644 # First create an AuthNRequest 645 request_proc = RequestProcessor(self.source, http_request, "test_state") 646 request = request_proc.build_auth_n() 647 648 # To get an assertion we need a parsed request (parsed by provider) 649 parsed_request = AuthNRequestParser(self.provider).parse( 650 b64encode(request.encode()).decode(), "test_state" 651 ) 652 # Now create a response and convert it to string (provider) 653 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 654 response = response_proc.build_response() 655 656 # Verify the response contains EncryptedAssertion 657 response_xml = fromstring(response) 658 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 659 660 # Now parse the response (source) - this will decrypt and verify assertion signature 661 http_request.POST = QueryDict(mutable=True) 662 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 663 664 response_parser = ResponseProcessor(self.source, http_request) 665 response_parser.parse() 666 667 def test_request_sign_both_and_encrypt(self): 668 """Test SAML with both sign_assertion and sign_response enabled AND encryption. 669 670 This is the most complex scenario: assertion is signed, then encrypted, 671 then the response is signed. Both signatures should be valid. 672 """ 673 self.provider.sign_response = True 674 self.provider.sign_assertion = True 675 self.provider.encryption_kp = self.cert 676 self.provider.save() 677 self.source.encryption_kp = self.cert 678 self.source.signed_assertion = True 679 self.source.signed_response = True 680 self.source.save() 681 http_request = self.request_factory.get("/", user=get_anonymous_user()) 682 683 # First create an AuthNRequest 684 request_proc = RequestProcessor(self.source, http_request, "test_state") 685 request = request_proc.build_auth_n() 686 687 # To get an assertion we need a parsed request (parsed by provider) 688 parsed_request = AuthNRequestParser(self.provider).parse( 689 b64encode(request.encode()).decode(), "test_state" 690 ) 691 # Now create a response and convert it to string (provider) 692 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 693 response = response_proc.build_response() 694 695 # Verify the response contains EncryptedAssertion and response signature 696 response_xml = fromstring(response) 697 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 698 self.assertEqual( 699 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 700 ) 701 702 # Now parse the response (source) - this will verify response signature, 703 # decrypt, then verify assertion signature 704 http_request.POST = QueryDict(mutable=True) 705 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 706 707 response_parser = ResponseProcessor(self.source, http_request) 708 response_parser.parse() 709 710 def test_encrypted_assertion_namespace_preservation(self): 711 """Test that encrypted assertions include namespace declarations. 712 713 When an assertion is encrypted, the resulting decrypted XML must include 714 the necessary namespace declarations (xmlns:saml) since it's now a standalone 715 document fragment, no longer inheriting namespaces from the parent Response. 716 """ 717 self.provider.encryption_kp = self.cert 718 self.provider.save() 719 self.source.encryption_kp = self.cert 720 self.source.save() 721 http_request = self.request_factory.get("/", user=get_anonymous_user()) 722 723 # First create an AuthNRequest 724 request_proc = RequestProcessor(self.source, http_request, "test_state") 725 request = request_proc.build_auth_n() 726 727 # To get an assertion we need a parsed request (parsed by provider) 728 parsed_request = AuthNRequestParser(self.provider).parse( 729 b64encode(request.encode()).decode(), "test_state" 730 ) 731 # Now create a response and convert it to string (provider) 732 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 733 response = response_proc.build_response() 734 735 # Parse the encrypted response 736 response_xml = fromstring(response) 737 encrypted_assertion = response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)[0] 738 encrypted_data = encrypted_assertion.xpath("//xenc:EncryptedData", namespaces=NS_MAP)[0] 739 740 # Decrypt the assertion manually to verify namespace is present 741 import xmlsec 742 743 manager = xmlsec.KeysManager() 744 key = xmlsec.Key.from_memory(self.cert.key_data, xmlsec.constants.KeyDataFormatPem, None) 745 manager.add_key(key) 746 enc_ctx = xmlsec.EncryptionContext(manager) 747 decrypted = enc_ctx.decrypt(encrypted_data) 748 749 # The decrypted assertion should have xmlns:saml namespace declaration 750 decrypted_str = etree.tostring(decrypted).decode() 751 self.assertIn("xmlns:saml", decrypted_str) 752 753 # Also verify full round-trip works (source can parse it) 754 http_request.POST = QueryDict(mutable=True) 755 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 756 757 response_parser = ResponseProcessor(self.source, http_request) 758 response_parser.parse() 759 760 def test_encrypted_response_schema_validation(self): 761 """Test that encrypted SAML responses validate against the SAML schema. 762 763 The response with EncryptedAssertion must be valid per saml-schema-protocol-2.0.xsd. 764 This ensures we don't have invalid elements like EncryptedData inside Assertion. 765 """ 766 self.provider.encryption_kp = self.cert 767 self.provider.save() 768 http_request = self.request_factory.get("/", user=get_anonymous_user()) 769 770 # First create an AuthNRequest 771 request_proc = RequestProcessor(self.source, http_request, "test_state") 772 request = request_proc.build_auth_n() 773 774 # To get an assertion we need a parsed request (parsed by provider) 775 parsed_request = AuthNRequestParser(self.provider).parse( 776 b64encode(request.encode()).decode(), "test_state" 777 ) 778 # Now create a response and convert it to string (provider) 779 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 780 response = response_proc.build_response() 781 782 # Validate against SAML schema 783 schema = etree.XMLSchema( 784 etree.parse("schemas/saml-schema-protocol-2.0.xsd", parser=etree.XMLParser()) # nosec 785 ) 786 self.assertTrue(schema.validate(lxml_from_string(response))) 787 788 # Verify structure: should have EncryptedAssertion, not Assertion with EncryptedData inside 789 response_xml = fromstring(response) 790 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 791 self.assertEqual(len(response_xml.xpath("//saml:Assertion", namespaces=NS_MAP)), 0) 792 793 def test_request_signed(self): 794 """Test full SAML Request/Response flow, fully signed""" 795 http_request = self.request_factory.get("/", user=get_anonymous_user()) 796 797 # First create an AuthNRequest 798 request_proc = RequestProcessor(self.source, http_request, "test_state") 799 request = request_proc.build_auth_n() 800 801 # To get an assertion we need a parsed request (parsed by provider) 802 parsed_request = AuthNRequestParser(self.provider).parse( 803 b64encode(request.encode()).decode(), "test_state" 804 ) 805 # Now create a response and convert it to string (provider) 806 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 807 response = response_proc.build_response() 808 809 # Now parse the response (source) 810 http_request.POST = QueryDict(mutable=True) 811 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 812 813 response_parser = ResponseProcessor(self.source, http_request) 814 response_parser.parse() 815 816 def test_request_signed_both(self): 817 """Test full SAML Request/Response flow, fully signed""" 818 self.provider.sign_assertion = True 819 self.provider.sign_response = True 820 self.provider.save() 821 self.source.signed_response = True 822 http_request = self.request_factory.get("/", user=get_anonymous_user()) 823 824 # First create an AuthNRequest 825 request_proc = RequestProcessor(self.source, http_request, "test_state") 826 request = request_proc.build_auth_n() 827 828 # To get an assertion we need a parsed request (parsed by provider) 829 parsed_request = AuthNRequestParser(self.provider).parse( 830 b64encode(request.encode()).decode(), "test_state" 831 ) 832 # Now create a response and convert it to string (provider) 833 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 834 response = response_proc.build_response() 835 # Ensure both response and assertion ID are in the response twice (once as ID attribute, 836 # once as ds:Reference URI) 837 self.assertEqual(response.count(response_proc._assertion_id), 2) 838 self.assertEqual(response.count(response_proc._response_id), 2) 839 840 schema = etree.XMLSchema( 841 etree.parse("schemas/saml-schema-protocol-2.0.xsd", parser=etree.XMLParser()) # nosec 842 ) 843 self.assertTrue(schema.validate(lxml_from_string(response))) 844 845 response_xml = fromstring(response) 846 self.assertEqual( 847 len(response_xml.xpath("//saml:Assertion/ds:Signature", namespaces=NS_MAP)), 1 848 ) 849 self.assertEqual( 850 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 851 ) 852 853 # Now parse the response (source) 854 http_request.POST = QueryDict(mutable=True) 855 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 856 857 response_parser = ResponseProcessor(self.source, http_request) 858 response_parser.parse() 859 860 def test_request_id_invalid(self): 861 """Test generated AuthNRequest with invalid request ID""" 862 http_request = self.request_factory.get("/", user=get_anonymous_user()) 863 864 # First create an AuthNRequest 865 request_proc = RequestProcessor(self.source, http_request, "test_state") 866 request = request_proc.build_auth_n() 867 868 # change the request ID 869 http_request.session[SESSION_KEY_REQUEST_ID] = "test" 870 http_request.session.save() 871 872 # To get an assertion we need a parsed request (parsed by provider) 873 parsed_request = AuthNRequestParser(self.provider).parse( 874 b64encode(request.encode()).decode(), "test_state" 875 ) 876 # Now create a response and convert it to string (provider) 877 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 878 response = response_proc.build_response() 879 880 # Now parse the response (source) 881 http_request.POST = QueryDict(mutable=True) 882 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 883 884 response_parser = ResponseProcessor(self.source, http_request) 885 886 with self.assertRaises(MismatchedRequestID): 887 response_parser.parse() 888 889 def test_signed_valid_detached(self): 890 """Test generated AuthNRequest with valid signature (detached)""" 891 http_request = self.request_factory.get("/") 892 893 # First create an AuthNRequest 894 request_proc = RequestProcessor(self.source, http_request, "test_state") 895 params = request_proc.build_auth_n_detached() 896 # Now we check the ID and signature 897 parsed_request = AuthNRequestParser(self.provider).parse_detached( 898 params["SAMLRequest"], 899 params["RelayState"], 900 params["Signature"], 901 params["SigAlg"], 902 ) 903 self.assertEqual(parsed_request.id, request_proc.request_id) 904 self.assertEqual(parsed_request.relay_state, "test_state") 905 906 def test_signed_detached_static(self): 907 """Test request with detached signature, 908 taken from https://www.samltool.com/generic_sso_req.php""" 909 static_keypair = CertificateKeyPair.objects.create( 910 name="samltool", certificate_data=REDIRECT_CERT 911 ) 912 provider = SAMLProvider( 913 name="samltool", 914 authorization_flow=create_test_flow(), 915 acs_url="https://10.120.20.200/saml-sp/SAML2/POST", 916 audience="https://10.120.20.200/saml-sp/SAML2/POST", 917 issuer_override="https://10.120.20.200/saml-sp/SAML2/POST", 918 signing_kp=static_keypair, 919 verification_kp=static_keypair, 920 ) 921 parsed_request = AuthNRequestParser(provider).parse_detached( 922 REDIRECT_REQUEST, REDIRECT_RELAY_STATE, REDIRECT_SIGNATURE, REDIRECT_SIG_ALG 923 ) 924 self.assertEqual(parsed_request.id, "_dcf55fcd27a887e60a7ef9ee6fd3adab") 925 self.assertEqual(parsed_request.name_id_policy, SAML_NAME_ID_FORMAT_UNSPECIFIED) 926 self.assertEqual(parsed_request.relay_state, REDIRECT_RELAY_STATE) 927 928 def test_signed_static(self): 929 """Test post request with static request""" 930 provider = SAMLProvider( 931 name="aws", 932 authorization_flow=create_test_flow(), 933 acs_url=( 934 "https://eu-central-1.signin.aws.amazon.com/platform/" 935 "saml/acs/2d737f96-55fb-4035-953e-5e24134eb778" 936 ), 937 audience="https://10.120.20.200/saml-sp/SAML2/POST", 938 issuer_override="https://10.120.20.200/saml-sp/SAML2/POST", 939 signing_kp=create_test_cert(), 940 ) 941 parsed_request = AuthNRequestParser(provider).parse(POST_REQUEST) 942 self.assertEqual(parsed_request.id, "aws_LDxLGeubpc5lx12gxCgS6uPbix1yd5re") 943 self.assertEqual(parsed_request.name_id_policy, SAML_NAME_ID_FORMAT_EMAIL) 944 945 def test_authn_context_class_ref_mapping(self): 946 """Test custom authn_context_class_ref""" 947 authn_context_class_ref = generate_id() 948 mapping = SAMLPropertyMapping.objects.create( 949 name=generate_id(), expression=f"""return '{authn_context_class_ref}'""" 950 ) 951 self.provider.authn_context_class_ref_mapping = mapping 952 self.provider.save() 953 user = create_test_admin_user() 954 http_request = self.request_factory.get("/", user=user) 955 956 # First create an AuthNRequest 957 request_proc = RequestProcessor(self.source, http_request, "test_state") 958 request = request_proc.build_auth_n() 959 960 # To get an assertion we need a parsed request (parsed by provider) 961 parsed_request = AuthNRequestParser(self.provider).parse( 962 b64encode(request.encode()).decode(), "test_state" 963 ) 964 # Now create a response and convert it to string (provider) 965 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 966 response = response_proc.build_response() 967 self.assertIn(user.username, response) 968 self.assertIn(authn_context_class_ref, response) 969 970 def test_authn_context_class_ref_mapping_invalid(self): 971 """Test custom authn_context_class_ref (invalid)""" 972 mapping = SAMLPropertyMapping.objects.create(name=generate_id(), expression="q") 973 self.provider.authn_context_class_ref_mapping = mapping 974 self.provider.save() 975 user = create_test_admin_user() 976 http_request = self.request_factory.get("/", user=user) 977 978 # First create an AuthNRequest 979 request_proc = RequestProcessor(self.source, http_request, "test_state") 980 request = request_proc.build_auth_n() 981 982 # To get an assertion we need a parsed request (parsed by provider) 983 parsed_request = AuthNRequestParser(self.provider).parse( 984 b64encode(request.encode()).decode(), "test_state" 985 ) 986 # Now create a response and convert it to string (provider) 987 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 988 response = response_proc.build_response() 989 self.assertIn(user.username, response) 990 991 events = Event.objects.filter( 992 action=EventAction.CONFIGURATION_ERROR, 993 ) 994 self.assertTrue(events.exists()) 995 self.assertEqual( 996 events.first().context["message"], 997 f"Failed to evaluate property-mapping: '{mapping.name}'", 998 ) 999 1000 def test_request_attributes(self): 1001 """Test full SAML Request/Response flow, fully signed""" 1002 user = create_test_admin_user() 1003 http_request = self.request_factory.get("/", user=user) 1004 1005 # First create an AuthNRequest 1006 request_proc = RequestProcessor(self.source, http_request, "test_state") 1007 request = request_proc.build_auth_n() 1008 1009 # To get an assertion we need a parsed request (parsed by provider) 1010 parsed_request = AuthNRequestParser(self.provider).parse( 1011 b64encode(request.encode()).decode(), "test_state" 1012 ) 1013 # Now create a response and convert it to string (provider) 1014 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 1015 self.assertIn(user.username, response_proc.build_response()) 1016 1017 def test_request_attributes_invalid(self): 1018 """Test full SAML Request/Response flow, fully signed""" 1019 user = create_test_admin_user() 1020 http_request = self.request_factory.get("/", user=user) 1021 1022 # First create an AuthNRequest 1023 request_proc = RequestProcessor(self.source, http_request, "test_state") 1024 request = request_proc.build_auth_n() 1025 1026 # Create invalid PropertyMapping 1027 mapping = SAMLPropertyMapping.objects.create( 1028 name=generate_id(), saml_name="test", expression="q" 1029 ) 1030 self.provider.property_mappings.add(mapping) 1031 1032 # To get an assertion we need a parsed request (parsed by provider) 1033 parsed_request = AuthNRequestParser(self.provider).parse( 1034 b64encode(request.encode()).decode(), "test_state" 1035 ) 1036 # Now create a response and convert it to string (provider) 1037 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 1038 self.assertIn(user.username, response_proc.build_response()) 1039 1040 events = Event.objects.filter( 1041 action=EventAction.CONFIGURATION_ERROR, 1042 ) 1043 self.assertTrue(events.exists()) 1044 self.assertEqual( 1045 events.first().context["message"], 1046 f"Failed to evaluate property-mapping: '{mapping.name}'", 1047 ) 1048 1049 def test_idp_initiated(self): 1050 """Test IDP-initiated login""" 1051 self.provider.default_relay_state = generate_id() 1052 request = AuthNRequestParser(self.provider).idp_initiated() 1053 self.assertEqual(request.id, None) 1054 self.assertEqual(request.relay_state, self.provider.default_relay_state) 1055 self.assertFalse(request.force_authn) 1056 1057 def test_force_authn(self): 1058 """Test that ForceAuthn from the SP is parsed from the AuthNRequest""" 1059 self.source.force_authn = True 1060 self.source.save() 1061 http_request = self.request_factory.get("/") 1062 1063 request_proc = RequestProcessor(self.source, http_request, "test_state") 1064 request = request_proc.build_auth_n() 1065 parsed_request = AuthNRequestParser(self.provider).parse( 1066 b64encode(request.encode()).decode(), "test_state" 1067 ) 1068 self.assertTrue(parsed_request.force_authn) 1069 1070 def _sso_redirect_with_force_authn(self): 1071 """Send an SP-initiated Redirect binding AuthnRequest with ForceAuthn="true" from a 1072 logged-in session and return the response.""" 1073 self.source.force_authn = True 1074 self.source.save() 1075 self.provider.authentication_flow = create_test_flow() 1076 self.provider.save() 1077 for flow in (self.provider.authorization_flow, self.provider.authentication_flow): 1078 FlowStageBinding.objects.create( 1079 target=flow, 1080 stage=DummyStage.objects.create(name=generate_id()), 1081 order=0, 1082 ) 1083 http_request = self.request_factory.get("/") 1084 params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() 1085 self.client.force_login(create_test_admin_user()) 1086 return self.client.get( 1087 reverse( 1088 "authentik_providers_saml:sso-redirect", 1089 kwargs={"application_slug": "test-app"}, 1090 ), 1091 params, 1092 ) 1093 1094 def test_force_authn_honored(self): 1095 """Test that ForceAuthn triggers re-authentication by default""" 1096 response = self._sso_redirect_with_force_authn() 1097 1098 self.assertEqual(response.status_code, 302) 1099 self.assertIn(self.provider.authentication_flow.slug, response["Location"]) 1100 self.assertIn(SESSION_KEY_LAST_LOGIN_UID, self.client.session) 1101 1102 def test_force_authn_ignored(self): 1103 """Test that ForceAuthn is ignored when the provider is configured to do so""" 1104 self.provider.ignore_force_authn = True 1105 self.provider.save() 1106 response = self._sso_redirect_with_force_authn() 1107 1108 self.assertEqual(response.status_code, 302) 1109 self.assertIn(self.provider.authorization_flow.slug, response["Location"]) 1110 self.assertNotIn(self.provider.authentication_flow.slug, response["Location"]) 1111 self.assertNotIn(SESSION_KEY_LAST_LOGIN_UID, self.client.session) 1112 1113 def test_doctype(self): 1114 """Test that a request with a document type declaration is refused""" 1115 request = ( 1116 '<?xml version="1.0"?>' 1117 "<!DOCTYPE samlp:AuthnRequest>" 1118 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1119 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1120 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1121 ) 1122 1123 with self.assertRaises(CannotHandleAssertion) as ctx: 1124 AuthNRequestParser(self.provider).parse(b64encode(request.encode()).decode()) 1125 # The user-facing message is generic; the parser's reason only goes to the detail 1126 self.assertEqual(str(ctx.exception), str(ERROR_CANNOT_DECODE_REQUEST)) 1127 self.assertIn("XML document contains a DOCTYPE declaration", str(ctx.exception.detail)) 1128 1129 def test_invalid_base64(self): 1130 """Test that a SAMLRequest that is not valid base64 is rejected, not a server error""" 1131 for parse in ( 1132 lambda: AuthNRequestParser(self.provider).parse("%%%not-base64%%%"), 1133 lambda: AuthNRequestParser(self.provider).parse_detached("%%%not-base64%%%", None), 1134 ): 1135 with self.assertRaises(CannotHandleAssertion) as ctx: 1136 parse() 1137 self.assertEqual(str(ctx.exception), str(ERROR_CANNOT_DECODE_REQUEST)) 1138 self.assertIn("base64", str(ctx.exception.detail)) 1139 1140 def test_acs_url_mismatch(self): 1141 """Test that a mismatched ACS URL is rejected without echoing either URL to the user""" 1142 # Unsigned request, so the ACS check is reached instead of the signature check 1143 self.provider.verification_kp = None 1144 self.provider.save() 1145 request = ( 1146 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1147 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1148 'AssertionConsumerServiceURL="https://evil.example.com/acs"/>' 1149 ) 1150 1151 with self.assertRaises(CannotHandleAssertion) as ctx: 1152 AuthNRequestParser(self.provider).parse(b64encode(request.encode()).decode()) 1153 self.assertEqual(str(ctx.exception), str(ERROR_ACS_URL_MISMATCH)) 1154 self.assertNotIn("evil.example.com", str(ctx.exception)) 1155 self.assertIn("https://evil.example.com/acs", ctx.exception.detail) 1156 self.assertIn(self.provider.acs_url, ctx.exception.detail) 1157 1158 def test_malformed_unsigned(self): 1159 """Test that malformed requests to a provider without a verification certificate are 1160 rejected with a handled error instead of a server error""" 1161 self.provider.verification_kp = None 1162 self.provider.save() 1163 missing_id = ( 1164 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1165 'Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1166 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1167 ) 1168 parser = AuthNRequestParser(self.provider) 1169 for payload in ("this is not xml", missing_id): 1170 with self.subTest(payload=payload, binding="post"): 1171 with self.assertRaisesMessage( 1172 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1173 ): 1174 parser.parse(b64encode(payload.encode()).decode()) 1175 with self.subTest(payload=payload, binding="redirect"): 1176 with self.assertRaisesMessage( 1177 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1178 ): 1179 parser.parse_detached(deflate_and_base64_encode(payload), None) 1180 1181 for binding, method in (("post", parser.parse), ("redirect", parser.parse_detached)): 1182 with self.subTest(payload="not base64", binding=binding): 1183 with self.assertRaisesMessage( 1184 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1185 ): 1186 method("%%%not-base64%%%", None) 1187 1188 def test_redirect_over_size_limit(self): 1189 """Test that a redirect-binding request that inflates beyond the size limit is refused""" 1190 request = deflate_and_base64_encode( 1191 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1192 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1193 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1194 + " " * (32 * 1024 * 1024) 1195 ) 1196 1197 tracemalloc.start() 1198 self.addCleanup(tracemalloc.stop) 1199 with self.assertRaises(CannotHandleAssertion): 1200 AuthNRequestParser(self.provider).parse_detached(request, None) 1201 _, peak = tracemalloc.get_traced_memory() 1202 1203 self.assertLess(peak, 32 * 1024 * 1024)
Test AuthN Request generator and parser
120 @apply_blueprint("system/providers-saml.yaml") 121 def setUp(self): 122 self.request_factory = RequestFactory() 123 self.cert = create_test_cert() 124 self.provider: SAMLProvider = SAMLProvider.objects.create( 125 authorization_flow=create_test_flow(), 126 acs_url="http://testserver/source/saml/provider/acs/", 127 signing_kp=self.cert, 128 verification_kp=self.cert, 129 ) 130 self.provider.property_mappings.set(SAMLPropertyMapping.objects.all()) 131 self.provider.save() 132 Application.objects.create( 133 name="test-app", 134 slug="test-app", 135 provider=self.provider, 136 ) 137 self.source = SAMLSource.objects.create( 138 slug="provider", 139 issuer_override="authentik", 140 pre_authentication_flow=create_test_flow(), 141 signing_kp=self.cert, 142 verification_kp=self.cert, 143 signed_assertion=True, 144 binding_type=SAMLBindingTypes.POST, 145 )
Hook method for setting up the test fixture before exercising it.
147 def post_authn_request(self, application_slug: str = "test-app", relay_state="test_state"): 148 """Send an SP-initiated AuthnRequest using the HTTP-POST binding.""" 149 request = RequestProcessor( 150 self.source, self.request_factory.get("/"), relay_state 151 ).build_auth_n() 152 return self.client.post( 153 reverse( 154 "authentik_providers_saml:sso-post", 155 kwargs={"application_slug": application_slug}, 156 ), 157 { 158 "SAMLRequest": b64encode(request.encode()).decode(), 159 "RelayState": relay_state, 160 }, 161 )
Send an SP-initiated AuthnRequest using the HTTP-POST binding.
163 def bind_excluded_consent_stage(self): 164 """Bind a consent stage to the authorization flow whose policy excludes every user 165 while the flow is planned.""" 166 binding = FlowStageBinding.objects.create( 167 target=self.provider.authorization_flow, 168 stage=ConsentStage.objects.create(name=generate_id()), 169 order=0, 170 evaluate_on_plan=True, 171 re_evaluate_policies=False, 172 ) 173 PolicyBinding.objects.create( 174 target=binding, 175 policy=DummyPolicy.objects.create( 176 name=generate_id(), result=False, wait_min=0, wait_max=1 177 ), 178 order=0, 179 )
Bind a consent stage to the authorization flow whose policy excludes every user while the flow is planned.
181 def executor_url(self, provider: SAMLProvider) -> str: 182 """Flow executor API URL for a provider's authorization flow.""" 183 return reverse( 184 "authentik_api:flow-executor", 185 kwargs={"flow_slug": provider.authorization_flow.slug}, 186 )
Flow executor API URL for a provider's authorization flow.
188 def assert_direct_post_response(self, response): 189 """Assert a direct SAML HTTP-POST response and its side effects.""" 190 self.assertEqual(response.status_code, 200) 191 self.assertTemplateUsed(response, "if/saml_form_post.html") 192 self.assertEqual(response.context_data["redirect_uri"], self.provider.acs_url) 193 self.assertEqual(response.context_data["attrs"]["RelayState"], "test_state") 194 self.assertIn("SAMLResponse", response.context_data["attrs"]) 195 self.assertIn("no-store", response["Cache-Control"]) 196 self.assertEqual(response["Pragma"], "no-cache") 197 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 198 self.assertTrue(SAMLSession.objects.filter(provider=self.provider).exists()) 199 self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists())
Assert a direct SAML HTTP-POST response and its side effects.
201 def test_post_response_empty_flow_is_direct(self): 202 """An empty authorization flow returns the SAML POST form directly.""" 203 self.provider.sp_binding = SAMLBindings.POST 204 self.provider.save() 205 self.client.force_login(create_test_admin_user()) 206 207 self.assert_direct_post_response(self.post_authn_request())
An empty authorization flow returns the SAML POST form directly.
209 def test_post_response_empty_flow_error_is_error_page(self): 210 """A direct SAML error renders an HTML error without exposing internal details.""" 211 self.provider.sp_binding = SAMLBindings.POST 212 self.provider.save() 213 self.client.force_login(create_test_admin_user()) 214 215 with patch.object( 216 AssertionProcessor, "build_response", side_effect=SAMLException("internal test error") 217 ): 218 response = self.post_authn_request() 219 220 self.assertEqual(response.status_code, 400) 221 self.assertTemplateUsed(response, "if/error.html") 222 self.assertContains(response, "Failed to process SAML assertion.", status_code=400) 223 self.assertNotContains(response, "internal test error", status_code=400) 224 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 225 self.assertFalse(SAMLSession.objects.filter(provider=self.provider).exists()) 226 self.assertTrue(Event.objects.filter(action=EventAction.CONFIGURATION_ERROR).exists())
A direct SAML error renders an HTML error without exposing internal details.
228 @patch_flag(ContinuousLogin, True) 229 def test_post_response_empty_flow_is_direct_with_continuous_login(self): 230 """Continuous login does not force an empty authorization flow into the executor.""" 231 self.provider.sp_binding = SAMLBindings.POST 232 self.provider.save() 233 self.client.force_login(create_test_admin_user()) 234 235 self.assert_direct_post_response(self.post_authn_request())
Continuous login does not force an empty authorization flow into the executor.
237 @patch_flag(ContinuousLogin, True) 238 def test_redirect_response_empty_flow_is_direct_with_continuous_login(self): 239 """An empty authorization flow returns the SAML Redirect response directly.""" 240 self.provider.sp_binding = SAMLBindings.REDIRECT 241 self.provider.save() 242 app = Application.objects.get(slug="test-app") 243 params = RequestProcessor( 244 self.source, self.request_factory.get("/"), "test_state" 245 ).build_auth_n_detached() 246 self.client.force_login(create_test_admin_user()) 247 248 response = self.client.get( 249 reverse( 250 "authentik_providers_saml:sso-redirect", 251 kwargs={"application_slug": app.slug}, 252 ), 253 params, 254 ) 255 256 self.assertEqual(response.status_code, 302) 257 redirect = urlparse(response["Location"]) 258 self.assertEqual( 259 f"{redirect.scheme}://{redirect.netloc}{redirect.path}", self.provider.acs_url 260 ) 261 redirect_query = parse_qs(redirect.query) 262 self.assertEqual(redirect_query["RelayState"], ["test_state"]) 263 self.assertIn("SAMLResponse", redirect_query) 264 self.assertNotIn(SESSION_KEY_PLAN, self.client.session) 265 self.assertTrue(SAMLSession.objects.filter(provider=self.provider).exists()) 266 self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists())
An empty authorization flow returns the SAML Redirect response directly.
268 def test_post_response_nonempty_flow_uses_executor(self): 269 """A configured authorization stage keeps using the flow executor.""" 270 self.provider.sp_binding = SAMLBindings.POST 271 self.provider.save() 272 FlowStageBinding.objects.create( 273 target=self.provider.authorization_flow, 274 stage=DummyStage.objects.create(name=generate_id()), 275 order=0, 276 ) 277 self.client.force_login(create_test_admin_user()) 278 279 response = self.post_authn_request() 280 281 self.assertEqual(response.status_code, 302) 282 self.assertEqual( 283 urlparse(response["Location"]).path, 284 reverse( 285 "authentik_core:if-flow", 286 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 287 ), 288 ) 289 self.assertIn(SESSION_KEY_PLAN, self.client.session)
A configured authorization stage keeps using the flow executor.
291 def test_post_response_excluded_stage_is_direct(self): 292 """A configured stage that policies exclude for this user doesn't need the executor.""" 293 self.provider.sp_binding = SAMLBindings.POST 294 self.provider.save() 295 self.bind_excluded_consent_stage() 296 self.client.force_login(create_test_admin_user()) 297 298 self.assert_direct_post_response(self.post_authn_request())
A configured stage that policies exclude for this user doesn't need the executor.
300 @patch_flag(ContinuousLogin, True) 301 def test_post_response_excluded_stage_uses_executor_with_continuous_login(self): 302 """With continuous login, a configured stage keeps the response in the flow executor 303 even when policies exclude it, since other tabs were told to wait for this flow.""" 304 self.provider.sp_binding = SAMLBindings.POST 305 self.provider.save() 306 self.bind_excluded_consent_stage() 307 self.client.force_login(create_test_admin_user()) 308 309 response = self.post_authn_request() 310 311 self.assertEqual(response.status_code, 302) 312 self.assertEqual( 313 urlparse(response["Location"]).path, 314 reverse( 315 "authentik_core:if-flow", 316 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 317 ), 318 ) 319 self.assertFalse(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists()) 320 challenge = self.client.get(self.executor_url(self.provider)).json() 321 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 322 self.assertEqual(challenge["url"], self.provider.acs_url)
With continuous login, a configured stage keeps the response in the flow executor even when policies exclude it, since other tabs were told to wait for this flow.
324 def test_post_to_executor_final_stage_does_not_reissue_assertion(self): 325 """A POST to the flow executor at the final stage keeps the challenge-response handling 326 instead of issuing another assertion.""" 327 self.provider.sp_binding = SAMLBindings.POST 328 self.provider.save() 329 FlowStageBinding.objects.create( 330 target=self.provider.authorization_flow, 331 stage=DummyStage.objects.create(name=generate_id()), 332 order=0, 333 ) 334 self.client.force_login(create_test_admin_user()) 335 self.post_authn_request() 336 executor_url = self.executor_url(self.provider) 337 self.client.get(executor_url) 338 self.client.post( 339 executor_url, {"component": "ak-stage-dummy"}, content_type="application/json" 340 ) 341 challenge = self.client.get(executor_url).json() 342 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 343 authorize_events = Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION) 344 self.assertEqual(authorize_events.count(), 1) 345 346 response = self.client.post( 347 executor_url, {"component": "ak-stage-autosubmit"}, content_type="application/json" 348 ) 349 350 self.assertEqual(response.status_code, 400) 351 self.assertEqual(authorize_events.count(), 1) 352 self.assertEqual(SAMLSession.objects.filter(provider=self.provider).count(), 1)
A POST to the flow executor at the final stage keeps the challenge-response handling instead of issuing another assertion.
354 def test_direct_post_response_keeps_other_tab_plan(self): 355 """A direct SAML response in one tab leaves the flow another tab is running intact.""" 356 self.provider.sp_binding = SAMLBindings.POST 357 self.provider.save() 358 FlowStageBinding.objects.create( 359 target=self.provider.authorization_flow, 360 stage=DummyStage.objects.create(name=generate_id()), 361 order=0, 362 ) 363 direct_provider = SAMLProvider.objects.create( 364 name=generate_id(), 365 authorization_flow=create_test_flow(), 366 acs_url=self.provider.acs_url, 367 sp_binding=SAMLBindings.POST, 368 signing_kp=self.cert, 369 verification_kp=self.cert, 370 ) 371 direct_provider.property_mappings.set(SAMLPropertyMapping.objects.all()) 372 Application.objects.create(name="direct-app", slug="direct-app", provider=direct_provider) 373 self.client.force_login(create_test_admin_user()) 374 375 # Tab A starts an authorization flow and stops at its first stage. 376 self.post_authn_request(relay_state="tab_a") 377 executor_url = self.executor_url(self.provider) 378 executor_query = {"query": "next=%2Ftab-a%2F"} 379 self.assertEqual( 380 self.client.get(executor_url, executor_query).json()["component"], "ak-stage-dummy" 381 ) 382 tab_a_plan = self.client.session[SESSION_KEY_PLAN] 383 tab_a_get = self.client.session[SESSION_KEY_GET] 384 385 # Tab B signs into an application with an empty authorization flow. 386 response = self.post_authn_request("direct-app", relay_state="tab_b") 387 self.assertTemplateUsed(response, "if/saml_form_post.html") 388 self.assertEqual(response.context_data["attrs"]["RelayState"], "tab_b") 389 self.assertTrue(SAMLSession.objects.filter(provider=direct_provider).exists()) 390 self.assertEqual(self.client.session[SESSION_KEY_PLAN].flow_pk, tab_a_plan.flow_pk) 391 self.assertEqual( 392 self.client.session[SESSION_KEY_PLAN].context[PLAN_CONTEXT_APPLICATION].slug, 393 "test-app", 394 ) 395 self.assertEqual(self.client.session[SESSION_KEY_GET], tab_a_get) 396 397 # Tab A finishes with its own request. 398 self.client.post( 399 executor_url, 400 {"component": "ak-stage-dummy"}, 401 content_type="application/json", 402 query_params=executor_query, 403 ) 404 challenge = self.client.get(executor_url, executor_query).json() 405 self.assertEqual(challenge["component"], "ak-stage-autosubmit") 406 self.assertEqual(challenge["url"], self.provider.acs_url) 407 self.assertEqual(challenge["attrs"]["RelayState"], "tab_a")
A direct SAML response in one tab leaves the flow another tab is running intact.
409 def test_signed_valid(self): 410 """Test generated AuthNRequest with valid signature""" 411 http_request = self.request_factory.get("/") 412 413 # First create an AuthNRequest 414 request_proc = RequestProcessor(self.source, http_request, "test_state") 415 auth_n = request_proc.get_auth_n() 416 self.assertEqual(auth_n.attrib["ProtocolBinding"], SAML_BINDING_POST) 417 418 request = request_proc.build_auth_n() 419 # Now we check the ID and signature 420 parsed_request = AuthNRequestParser(self.provider).parse( 421 b64encode(request.encode()).decode(), "test_state" 422 ) 423 self.assertEqual(parsed_request.id, request_proc.request_id) 424 self.assertEqual(parsed_request.relay_state, "test_state")
Test generated AuthNRequest with valid signature
426 def test_redirect_binding_flow_redirect_includes_resume_url(self): 427 """Test SP-initiated Redirect binding keeps the original SAML URL as next.""" 428 app = Application.objects.get(slug="test-app") 429 FlowStageBinding.objects.create( 430 target=self.provider.authorization_flow, 431 stage=DummyStage.objects.create(name=generate_id()), 432 order=0, 433 ) 434 http_request = self.request_factory.get("/") 435 params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() 436 self.client.force_login(create_test_admin_user()) 437 url = reverse( 438 "authentik_providers_saml:sso-redirect", 439 kwargs={"application_slug": app.slug}, 440 ) 441 442 response = self.client.get(url, params) 443 444 self.assertEqual(response.status_code, 302) 445 redirect_query = parse_qs(urlparse(response["Location"]).query) 446 self.assertIn("next", redirect_query) 447 448 next_url = urlparse(redirect_query["next"][0]) 449 self.assertEqual(next_url.path, url) 450 next_query = parse_qs(next_url.query) 451 for key, value in params.items(): 452 self.assertEqual(next_query[key], [value])
Test SP-initiated Redirect binding keeps the original SAML URL as next.
454 @patch_flag(ContinuousLogin, True) 455 def test_redirect_binding_continuous_login_final_redirect(self): 456 """Test SP-initiated Redirect binding returns a final redirect challenge under 457 continuous login, instead of an un-validated-serializer error.""" 458 self.provider.sp_binding = SAMLBindings.REDIRECT 459 self.provider.save() 460 FlowStageBinding.objects.create( 461 target=self.provider.authorization_flow, 462 stage=DummyStage.objects.create(name=generate_id()), 463 order=0, 464 ) 465 app = Application.objects.get(slug="test-app") 466 http_request = self.request_factory.get("/") 467 params = RequestProcessor(self.source, http_request, "test_state").build_auth_n_detached() 468 self.client.force_login(create_test_admin_user()) 469 470 # Initiate the SP-initiated request, which plans the flow and redirects into the executor. 471 initiate = self.client.get( 472 reverse( 473 "authentik_providers_saml:sso-redirect", 474 kwargs={"application_slug": app.slug}, 475 ), 476 params, 477 ) 478 self.assertEqual(initiate.status_code, 302) 479 480 # Drive the flow executor to completion, reaching SAMLFlowFinalView. 481 executor_url = reverse( 482 "authentik_api:flow-executor", 483 kwargs={"flow_slug": self.provider.authorization_flow.slug}, 484 ) 485 challenge = self.client.get(executor_url) 486 self.assertEqual(challenge.json()["component"], "ak-stage-dummy") 487 advance = self.client.post( 488 executor_url, 489 {"component": "ak-stage-dummy"}, 490 content_type="application/json", 491 ) 492 self.assertEqual(advance.status_code, 302) 493 response = self.client.get(executor_url) 494 495 self.assertEqual(response.status_code, 200) 496 body = loads(response.content.decode()) 497 self.assertEqual(body["component"], "xak-flow-redirect") 498 self.assertTrue(body["final_redirect"]) 499 self.assertNotIn("continuous_login_hold", body) 500 self.assertTrue(body["to"].startswith(self.provider.acs_url))
Test SP-initiated Redirect binding returns a final redirect challenge under continuous login, instead of an un-validated-serializer error.
502 def test_request_encrypt(self): 503 """Test full SAML Request/Response flow, fully encrypted, for each supported algorithm""" 504 self.source.encryption_kp = self.cert 505 self.source.save() 506 for algorithm in (AES128_CBC, AES256_CBC, AES128_GCM, AES256_GCM): 507 with self.subTest(algorithm=algorithm): 508 self.provider.encryption_kp = self.cert 509 self.provider.encryption_algorithm = algorithm 510 self.provider.save() 511 http_request = self.request_factory.get("/", user=get_anonymous_user()) 512 513 # First create an AuthNRequest 514 request_proc = RequestProcessor(self.source, http_request, "test_state") 515 request = request_proc.build_auth_n() 516 517 # To get an assertion we need a parsed request (parsed by provider) 518 parsed_request = AuthNRequestParser(self.provider).parse( 519 b64encode(request.encode()).decode(), "test_state" 520 ) 521 # Now create a response and convert it to string (provider) 522 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 523 response = response_proc.build_response() 524 525 # The chosen algorithm must be the one advertised on the wire 526 response_xml = lxml_from_string(response.encode()) 527 self.assertEqual( 528 response_xml.xpath( 529 "//xenc:EncryptedData/xenc:EncryptionMethod/@Algorithm", 530 namespaces=NS_MAP, 531 ), 532 [algorithm], 533 ) 534 535 # Now parse the response (source), which decrypts the assertion 536 http_request.POST = QueryDict(mutable=True) 537 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 538 539 response_parser = ResponseProcessor(self.source, http_request) 540 response_parser.parse()
Test full SAML Request/Response flow, fully encrypted, for each supported algorithm
542 def test_request_encrypt_cert_only(self): 543 """Test SAML encryption with certificate-only keypair (no private key). 544 545 This tests the scenario where the IdP (provider) only has the SP's public 546 certificate for encryption, without a private key. This is the expected 547 real-world scenario since the SP would never share their private key. 548 """ 549 # Create a full keypair for the source (SP) - it needs the private key to decrypt 550 full_keypair = create_test_cert() 551 552 # Create a certificate-only keypair for the provider (IdP) 553 # This simulates having only the SP's public certificate 554 cert_only = CertificateKeyPair.objects.create( 555 name=generate_id(), 556 certificate_data=full_keypair.certificate_data, 557 key_data="", # No private key 558 ) 559 560 self.provider.encryption_kp = cert_only 561 self.provider.save() 562 self.source.encryption_kp = full_keypair 563 self.source.save() 564 http_request = self.request_factory.get("/", user=get_anonymous_user()) 565 566 # First create an AuthNRequest 567 request_proc = RequestProcessor(self.source, http_request, "test_state") 568 request = request_proc.build_auth_n() 569 570 # To get an assertion we need a parsed request (parsed by provider) 571 parsed_request = AuthNRequestParser(self.provider).parse( 572 b64encode(request.encode()).decode(), "test_state" 573 ) 574 # Now create a response and convert it to string (provider) 575 # This should work with only the certificate (public key) for encryption 576 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 577 response = response_proc.build_response() 578 579 # Now parse the response (source) - decryption requires the private key 580 http_request.POST = QueryDict(mutable=True) 581 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 582 583 response_parser = ResponseProcessor(self.source, http_request) 584 response_parser.parse()
Test SAML encryption with certificate-only keypair (no private key).
This tests the scenario where the IdP (provider) only has the SP's public certificate for encryption, without a private key. This is the expected real-world scenario since the SP would never share their private key.
586 def test_request_sign_response_and_encrypt(self): 587 """Test SAML with sign_response enabled AND encryption. 588 589 This tests the fix for signature invalidation when encryption is enabled. 590 The response must be signed AFTER encryption, not before, because encryption 591 replaces the Assertion with EncryptedAssertion which changes the response content. 592 """ 593 self.provider.sign_response = True 594 self.provider.sign_assertion = False 595 self.provider.encryption_kp = self.cert 596 self.provider.save() 597 self.source.encryption_kp = self.cert 598 self.source.signed_response = True 599 self.source.signed_assertion = False # Only response is signed, not assertion 600 self.source.save() 601 http_request = self.request_factory.get("/", user=get_anonymous_user()) 602 603 # First create an AuthNRequest 604 request_proc = RequestProcessor(self.source, http_request, "test_state") 605 request = request_proc.build_auth_n() 606 607 # To get an assertion we need a parsed request (parsed by provider) 608 parsed_request = AuthNRequestParser(self.provider).parse( 609 b64encode(request.encode()).decode(), "test_state" 610 ) 611 # Now create a response and convert it to string (provider) 612 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 613 response = response_proc.build_response() 614 615 # Verify the response contains EncryptedAssertion and a signature 616 response_xml = fromstring(response) 617 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 618 self.assertEqual( 619 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 620 ) 621 622 # Now parse the response (source) - this will verify the signature and decrypt 623 http_request.POST = QueryDict(mutable=True) 624 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 625 626 response_parser = ResponseProcessor(self.source, http_request) 627 response_parser.parse()
Test SAML with sign_response enabled AND encryption.
This tests the fix for signature invalidation when encryption is enabled. The response must be signed AFTER encryption, not before, because encryption replaces the Assertion with EncryptedAssertion which changes the response content.
629 def test_request_sign_assertion_and_encrypt(self): 630 """Test SAML with sign_assertion enabled AND encryption. 631 632 The assertion signature should be inside the encrypted content and 633 remain valid after decryption. 634 """ 635 self.provider.sign_response = False 636 self.provider.sign_assertion = True 637 self.provider.encryption_kp = self.cert 638 self.provider.save() 639 self.source.encryption_kp = self.cert 640 self.source.signed_assertion = True 641 self.source.save() 642 http_request = self.request_factory.get("/", user=get_anonymous_user()) 643 644 # First create an AuthNRequest 645 request_proc = RequestProcessor(self.source, http_request, "test_state") 646 request = request_proc.build_auth_n() 647 648 # To get an assertion we need a parsed request (parsed by provider) 649 parsed_request = AuthNRequestParser(self.provider).parse( 650 b64encode(request.encode()).decode(), "test_state" 651 ) 652 # Now create a response and convert it to string (provider) 653 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 654 response = response_proc.build_response() 655 656 # Verify the response contains EncryptedAssertion 657 response_xml = fromstring(response) 658 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 659 660 # Now parse the response (source) - this will decrypt and verify assertion signature 661 http_request.POST = QueryDict(mutable=True) 662 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 663 664 response_parser = ResponseProcessor(self.source, http_request) 665 response_parser.parse()
Test SAML with sign_assertion enabled AND encryption.
The assertion signature should be inside the encrypted content and remain valid after decryption.
667 def test_request_sign_both_and_encrypt(self): 668 """Test SAML with both sign_assertion and sign_response enabled AND encryption. 669 670 This is the most complex scenario: assertion is signed, then encrypted, 671 then the response is signed. Both signatures should be valid. 672 """ 673 self.provider.sign_response = True 674 self.provider.sign_assertion = True 675 self.provider.encryption_kp = self.cert 676 self.provider.save() 677 self.source.encryption_kp = self.cert 678 self.source.signed_assertion = True 679 self.source.signed_response = True 680 self.source.save() 681 http_request = self.request_factory.get("/", user=get_anonymous_user()) 682 683 # First create an AuthNRequest 684 request_proc = RequestProcessor(self.source, http_request, "test_state") 685 request = request_proc.build_auth_n() 686 687 # To get an assertion we need a parsed request (parsed by provider) 688 parsed_request = AuthNRequestParser(self.provider).parse( 689 b64encode(request.encode()).decode(), "test_state" 690 ) 691 # Now create a response and convert it to string (provider) 692 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 693 response = response_proc.build_response() 694 695 # Verify the response contains EncryptedAssertion and response signature 696 response_xml = fromstring(response) 697 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 698 self.assertEqual( 699 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 700 ) 701 702 # Now parse the response (source) - this will verify response signature, 703 # decrypt, then verify assertion signature 704 http_request.POST = QueryDict(mutable=True) 705 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 706 707 response_parser = ResponseProcessor(self.source, http_request) 708 response_parser.parse()
Test SAML with both sign_assertion and sign_response enabled AND encryption.
This is the most complex scenario: assertion is signed, then encrypted, then the response is signed. Both signatures should be valid.
710 def test_encrypted_assertion_namespace_preservation(self): 711 """Test that encrypted assertions include namespace declarations. 712 713 When an assertion is encrypted, the resulting decrypted XML must include 714 the necessary namespace declarations (xmlns:saml) since it's now a standalone 715 document fragment, no longer inheriting namespaces from the parent Response. 716 """ 717 self.provider.encryption_kp = self.cert 718 self.provider.save() 719 self.source.encryption_kp = self.cert 720 self.source.save() 721 http_request = self.request_factory.get("/", user=get_anonymous_user()) 722 723 # First create an AuthNRequest 724 request_proc = RequestProcessor(self.source, http_request, "test_state") 725 request = request_proc.build_auth_n() 726 727 # To get an assertion we need a parsed request (parsed by provider) 728 parsed_request = AuthNRequestParser(self.provider).parse( 729 b64encode(request.encode()).decode(), "test_state" 730 ) 731 # Now create a response and convert it to string (provider) 732 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 733 response = response_proc.build_response() 734 735 # Parse the encrypted response 736 response_xml = fromstring(response) 737 encrypted_assertion = response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)[0] 738 encrypted_data = encrypted_assertion.xpath("//xenc:EncryptedData", namespaces=NS_MAP)[0] 739 740 # Decrypt the assertion manually to verify namespace is present 741 import xmlsec 742 743 manager = xmlsec.KeysManager() 744 key = xmlsec.Key.from_memory(self.cert.key_data, xmlsec.constants.KeyDataFormatPem, None) 745 manager.add_key(key) 746 enc_ctx = xmlsec.EncryptionContext(manager) 747 decrypted = enc_ctx.decrypt(encrypted_data) 748 749 # The decrypted assertion should have xmlns:saml namespace declaration 750 decrypted_str = etree.tostring(decrypted).decode() 751 self.assertIn("xmlns:saml", decrypted_str) 752 753 # Also verify full round-trip works (source can parse it) 754 http_request.POST = QueryDict(mutable=True) 755 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 756 757 response_parser = ResponseProcessor(self.source, http_request) 758 response_parser.parse()
Test that encrypted assertions include namespace declarations.
When an assertion is encrypted, the resulting decrypted XML must include the necessary namespace declarations (xmlns:saml) since it's now a standalone document fragment, no longer inheriting namespaces from the parent Response.
760 def test_encrypted_response_schema_validation(self): 761 """Test that encrypted SAML responses validate against the SAML schema. 762 763 The response with EncryptedAssertion must be valid per saml-schema-protocol-2.0.xsd. 764 This ensures we don't have invalid elements like EncryptedData inside Assertion. 765 """ 766 self.provider.encryption_kp = self.cert 767 self.provider.save() 768 http_request = self.request_factory.get("/", user=get_anonymous_user()) 769 770 # First create an AuthNRequest 771 request_proc = RequestProcessor(self.source, http_request, "test_state") 772 request = request_proc.build_auth_n() 773 774 # To get an assertion we need a parsed request (parsed by provider) 775 parsed_request = AuthNRequestParser(self.provider).parse( 776 b64encode(request.encode()).decode(), "test_state" 777 ) 778 # Now create a response and convert it to string (provider) 779 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 780 response = response_proc.build_response() 781 782 # Validate against SAML schema 783 schema = etree.XMLSchema( 784 etree.parse("schemas/saml-schema-protocol-2.0.xsd", parser=etree.XMLParser()) # nosec 785 ) 786 self.assertTrue(schema.validate(lxml_from_string(response))) 787 788 # Verify structure: should have EncryptedAssertion, not Assertion with EncryptedData inside 789 response_xml = fromstring(response) 790 self.assertEqual(len(response_xml.xpath("//saml:EncryptedAssertion", namespaces=NS_MAP)), 1) 791 self.assertEqual(len(response_xml.xpath("//saml:Assertion", namespaces=NS_MAP)), 0)
Test that encrypted SAML responses validate against the SAML schema.
The response with EncryptedAssertion must be valid per saml-schema-protocol-2.0.xsd. This ensures we don't have invalid elements like EncryptedData inside Assertion.
793 def test_request_signed(self): 794 """Test full SAML Request/Response flow, fully signed""" 795 http_request = self.request_factory.get("/", user=get_anonymous_user()) 796 797 # First create an AuthNRequest 798 request_proc = RequestProcessor(self.source, http_request, "test_state") 799 request = request_proc.build_auth_n() 800 801 # To get an assertion we need a parsed request (parsed by provider) 802 parsed_request = AuthNRequestParser(self.provider).parse( 803 b64encode(request.encode()).decode(), "test_state" 804 ) 805 # Now create a response and convert it to string (provider) 806 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 807 response = response_proc.build_response() 808 809 # Now parse the response (source) 810 http_request.POST = QueryDict(mutable=True) 811 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 812 813 response_parser = ResponseProcessor(self.source, http_request) 814 response_parser.parse()
Test full SAML Request/Response flow, fully signed
816 def test_request_signed_both(self): 817 """Test full SAML Request/Response flow, fully signed""" 818 self.provider.sign_assertion = True 819 self.provider.sign_response = True 820 self.provider.save() 821 self.source.signed_response = True 822 http_request = self.request_factory.get("/", user=get_anonymous_user()) 823 824 # First create an AuthNRequest 825 request_proc = RequestProcessor(self.source, http_request, "test_state") 826 request = request_proc.build_auth_n() 827 828 # To get an assertion we need a parsed request (parsed by provider) 829 parsed_request = AuthNRequestParser(self.provider).parse( 830 b64encode(request.encode()).decode(), "test_state" 831 ) 832 # Now create a response and convert it to string (provider) 833 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 834 response = response_proc.build_response() 835 # Ensure both response and assertion ID are in the response twice (once as ID attribute, 836 # once as ds:Reference URI) 837 self.assertEqual(response.count(response_proc._assertion_id), 2) 838 self.assertEqual(response.count(response_proc._response_id), 2) 839 840 schema = etree.XMLSchema( 841 etree.parse("schemas/saml-schema-protocol-2.0.xsd", parser=etree.XMLParser()) # nosec 842 ) 843 self.assertTrue(schema.validate(lxml_from_string(response))) 844 845 response_xml = fromstring(response) 846 self.assertEqual( 847 len(response_xml.xpath("//saml:Assertion/ds:Signature", namespaces=NS_MAP)), 1 848 ) 849 self.assertEqual( 850 len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1 851 ) 852 853 # Now parse the response (source) 854 http_request.POST = QueryDict(mutable=True) 855 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 856 857 response_parser = ResponseProcessor(self.source, http_request) 858 response_parser.parse()
Test full SAML Request/Response flow, fully signed
860 def test_request_id_invalid(self): 861 """Test generated AuthNRequest with invalid request ID""" 862 http_request = self.request_factory.get("/", user=get_anonymous_user()) 863 864 # First create an AuthNRequest 865 request_proc = RequestProcessor(self.source, http_request, "test_state") 866 request = request_proc.build_auth_n() 867 868 # change the request ID 869 http_request.session[SESSION_KEY_REQUEST_ID] = "test" 870 http_request.session.save() 871 872 # To get an assertion we need a parsed request (parsed by provider) 873 parsed_request = AuthNRequestParser(self.provider).parse( 874 b64encode(request.encode()).decode(), "test_state" 875 ) 876 # Now create a response and convert it to string (provider) 877 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 878 response = response_proc.build_response() 879 880 # Now parse the response (source) 881 http_request.POST = QueryDict(mutable=True) 882 http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode() 883 884 response_parser = ResponseProcessor(self.source, http_request) 885 886 with self.assertRaises(MismatchedRequestID): 887 response_parser.parse()
Test generated AuthNRequest with invalid request ID
889 def test_signed_valid_detached(self): 890 """Test generated AuthNRequest with valid signature (detached)""" 891 http_request = self.request_factory.get("/") 892 893 # First create an AuthNRequest 894 request_proc = RequestProcessor(self.source, http_request, "test_state") 895 params = request_proc.build_auth_n_detached() 896 # Now we check the ID and signature 897 parsed_request = AuthNRequestParser(self.provider).parse_detached( 898 params["SAMLRequest"], 899 params["RelayState"], 900 params["Signature"], 901 params["SigAlg"], 902 ) 903 self.assertEqual(parsed_request.id, request_proc.request_id) 904 self.assertEqual(parsed_request.relay_state, "test_state")
Test generated AuthNRequest with valid signature (detached)
906 def test_signed_detached_static(self): 907 """Test request with detached signature, 908 taken from https://www.samltool.com/generic_sso_req.php""" 909 static_keypair = CertificateKeyPair.objects.create( 910 name="samltool", certificate_data=REDIRECT_CERT 911 ) 912 provider = SAMLProvider( 913 name="samltool", 914 authorization_flow=create_test_flow(), 915 acs_url="https://10.120.20.200/saml-sp/SAML2/POST", 916 audience="https://10.120.20.200/saml-sp/SAML2/POST", 917 issuer_override="https://10.120.20.200/saml-sp/SAML2/POST", 918 signing_kp=static_keypair, 919 verification_kp=static_keypair, 920 ) 921 parsed_request = AuthNRequestParser(provider).parse_detached( 922 REDIRECT_REQUEST, REDIRECT_RELAY_STATE, REDIRECT_SIGNATURE, REDIRECT_SIG_ALG 923 ) 924 self.assertEqual(parsed_request.id, "_dcf55fcd27a887e60a7ef9ee6fd3adab") 925 self.assertEqual(parsed_request.name_id_policy, SAML_NAME_ID_FORMAT_UNSPECIFIED) 926 self.assertEqual(parsed_request.relay_state, REDIRECT_RELAY_STATE)
Test request with detached signature, taken from https://www.samltool.com/generic_sso_req.php
928 def test_signed_static(self): 929 """Test post request with static request""" 930 provider = SAMLProvider( 931 name="aws", 932 authorization_flow=create_test_flow(), 933 acs_url=( 934 "https://eu-central-1.signin.aws.amazon.com/platform/" 935 "saml/acs/2d737f96-55fb-4035-953e-5e24134eb778" 936 ), 937 audience="https://10.120.20.200/saml-sp/SAML2/POST", 938 issuer_override="https://10.120.20.200/saml-sp/SAML2/POST", 939 signing_kp=create_test_cert(), 940 ) 941 parsed_request = AuthNRequestParser(provider).parse(POST_REQUEST) 942 self.assertEqual(parsed_request.id, "aws_LDxLGeubpc5lx12gxCgS6uPbix1yd5re") 943 self.assertEqual(parsed_request.name_id_policy, SAML_NAME_ID_FORMAT_EMAIL)
Test post request with static request
945 def test_authn_context_class_ref_mapping(self): 946 """Test custom authn_context_class_ref""" 947 authn_context_class_ref = generate_id() 948 mapping = SAMLPropertyMapping.objects.create( 949 name=generate_id(), expression=f"""return '{authn_context_class_ref}'""" 950 ) 951 self.provider.authn_context_class_ref_mapping = mapping 952 self.provider.save() 953 user = create_test_admin_user() 954 http_request = self.request_factory.get("/", user=user) 955 956 # First create an AuthNRequest 957 request_proc = RequestProcessor(self.source, http_request, "test_state") 958 request = request_proc.build_auth_n() 959 960 # To get an assertion we need a parsed request (parsed by provider) 961 parsed_request = AuthNRequestParser(self.provider).parse( 962 b64encode(request.encode()).decode(), "test_state" 963 ) 964 # Now create a response and convert it to string (provider) 965 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 966 response = response_proc.build_response() 967 self.assertIn(user.username, response) 968 self.assertIn(authn_context_class_ref, response)
Test custom authn_context_class_ref
970 def test_authn_context_class_ref_mapping_invalid(self): 971 """Test custom authn_context_class_ref (invalid)""" 972 mapping = SAMLPropertyMapping.objects.create(name=generate_id(), expression="q") 973 self.provider.authn_context_class_ref_mapping = mapping 974 self.provider.save() 975 user = create_test_admin_user() 976 http_request = self.request_factory.get("/", user=user) 977 978 # First create an AuthNRequest 979 request_proc = RequestProcessor(self.source, http_request, "test_state") 980 request = request_proc.build_auth_n() 981 982 # To get an assertion we need a parsed request (parsed by provider) 983 parsed_request = AuthNRequestParser(self.provider).parse( 984 b64encode(request.encode()).decode(), "test_state" 985 ) 986 # Now create a response and convert it to string (provider) 987 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 988 response = response_proc.build_response() 989 self.assertIn(user.username, response) 990 991 events = Event.objects.filter( 992 action=EventAction.CONFIGURATION_ERROR, 993 ) 994 self.assertTrue(events.exists()) 995 self.assertEqual( 996 events.first().context["message"], 997 f"Failed to evaluate property-mapping: '{mapping.name}'", 998 )
Test custom authn_context_class_ref (invalid)
1000 def test_request_attributes(self): 1001 """Test full SAML Request/Response flow, fully signed""" 1002 user = create_test_admin_user() 1003 http_request = self.request_factory.get("/", user=user) 1004 1005 # First create an AuthNRequest 1006 request_proc = RequestProcessor(self.source, http_request, "test_state") 1007 request = request_proc.build_auth_n() 1008 1009 # To get an assertion we need a parsed request (parsed by provider) 1010 parsed_request = AuthNRequestParser(self.provider).parse( 1011 b64encode(request.encode()).decode(), "test_state" 1012 ) 1013 # Now create a response and convert it to string (provider) 1014 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 1015 self.assertIn(user.username, response_proc.build_response())
Test full SAML Request/Response flow, fully signed
1017 def test_request_attributes_invalid(self): 1018 """Test full SAML Request/Response flow, fully signed""" 1019 user = create_test_admin_user() 1020 http_request = self.request_factory.get("/", user=user) 1021 1022 # First create an AuthNRequest 1023 request_proc = RequestProcessor(self.source, http_request, "test_state") 1024 request = request_proc.build_auth_n() 1025 1026 # Create invalid PropertyMapping 1027 mapping = SAMLPropertyMapping.objects.create( 1028 name=generate_id(), saml_name="test", expression="q" 1029 ) 1030 self.provider.property_mappings.add(mapping) 1031 1032 # To get an assertion we need a parsed request (parsed by provider) 1033 parsed_request = AuthNRequestParser(self.provider).parse( 1034 b64encode(request.encode()).decode(), "test_state" 1035 ) 1036 # Now create a response and convert it to string (provider) 1037 response_proc = AssertionProcessor(self.provider, http_request, parsed_request) 1038 self.assertIn(user.username, response_proc.build_response()) 1039 1040 events = Event.objects.filter( 1041 action=EventAction.CONFIGURATION_ERROR, 1042 ) 1043 self.assertTrue(events.exists()) 1044 self.assertEqual( 1045 events.first().context["message"], 1046 f"Failed to evaluate property-mapping: '{mapping.name}'", 1047 )
Test full SAML Request/Response flow, fully signed
1049 def test_idp_initiated(self): 1050 """Test IDP-initiated login""" 1051 self.provider.default_relay_state = generate_id() 1052 request = AuthNRequestParser(self.provider).idp_initiated() 1053 self.assertEqual(request.id, None) 1054 self.assertEqual(request.relay_state, self.provider.default_relay_state) 1055 self.assertFalse(request.force_authn)
Test IDP-initiated login
1057 def test_force_authn(self): 1058 """Test that ForceAuthn from the SP is parsed from the AuthNRequest""" 1059 self.source.force_authn = True 1060 self.source.save() 1061 http_request = self.request_factory.get("/") 1062 1063 request_proc = RequestProcessor(self.source, http_request, "test_state") 1064 request = request_proc.build_auth_n() 1065 parsed_request = AuthNRequestParser(self.provider).parse( 1066 b64encode(request.encode()).decode(), "test_state" 1067 ) 1068 self.assertTrue(parsed_request.force_authn)
Test that ForceAuthn from the SP is parsed from the AuthNRequest
1094 def test_force_authn_honored(self): 1095 """Test that ForceAuthn triggers re-authentication by default""" 1096 response = self._sso_redirect_with_force_authn() 1097 1098 self.assertEqual(response.status_code, 302) 1099 self.assertIn(self.provider.authentication_flow.slug, response["Location"]) 1100 self.assertIn(SESSION_KEY_LAST_LOGIN_UID, self.client.session)
Test that ForceAuthn triggers re-authentication by default
1102 def test_force_authn_ignored(self): 1103 """Test that ForceAuthn is ignored when the provider is configured to do so""" 1104 self.provider.ignore_force_authn = True 1105 self.provider.save() 1106 response = self._sso_redirect_with_force_authn() 1107 1108 self.assertEqual(response.status_code, 302) 1109 self.assertIn(self.provider.authorization_flow.slug, response["Location"]) 1110 self.assertNotIn(self.provider.authentication_flow.slug, response["Location"]) 1111 self.assertNotIn(SESSION_KEY_LAST_LOGIN_UID, self.client.session)
Test that ForceAuthn is ignored when the provider is configured to do so
1113 def test_doctype(self): 1114 """Test that a request with a document type declaration is refused""" 1115 request = ( 1116 '<?xml version="1.0"?>' 1117 "<!DOCTYPE samlp:AuthnRequest>" 1118 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1119 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1120 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1121 ) 1122 1123 with self.assertRaises(CannotHandleAssertion) as ctx: 1124 AuthNRequestParser(self.provider).parse(b64encode(request.encode()).decode()) 1125 # The user-facing message is generic; the parser's reason only goes to the detail 1126 self.assertEqual(str(ctx.exception), str(ERROR_CANNOT_DECODE_REQUEST)) 1127 self.assertIn("XML document contains a DOCTYPE declaration", str(ctx.exception.detail))
Test that a request with a document type declaration is refused
1129 def test_invalid_base64(self): 1130 """Test that a SAMLRequest that is not valid base64 is rejected, not a server error""" 1131 for parse in ( 1132 lambda: AuthNRequestParser(self.provider).parse("%%%not-base64%%%"), 1133 lambda: AuthNRequestParser(self.provider).parse_detached("%%%not-base64%%%", None), 1134 ): 1135 with self.assertRaises(CannotHandleAssertion) as ctx: 1136 parse() 1137 self.assertEqual(str(ctx.exception), str(ERROR_CANNOT_DECODE_REQUEST)) 1138 self.assertIn("base64", str(ctx.exception.detail))
Test that a SAMLRequest that is not valid base64 is rejected, not a server error
1140 def test_acs_url_mismatch(self): 1141 """Test that a mismatched ACS URL is rejected without echoing either URL to the user""" 1142 # Unsigned request, so the ACS check is reached instead of the signature check 1143 self.provider.verification_kp = None 1144 self.provider.save() 1145 request = ( 1146 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1147 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1148 'AssertionConsumerServiceURL="https://evil.example.com/acs"/>' 1149 ) 1150 1151 with self.assertRaises(CannotHandleAssertion) as ctx: 1152 AuthNRequestParser(self.provider).parse(b64encode(request.encode()).decode()) 1153 self.assertEqual(str(ctx.exception), str(ERROR_ACS_URL_MISMATCH)) 1154 self.assertNotIn("evil.example.com", str(ctx.exception)) 1155 self.assertIn("https://evil.example.com/acs", ctx.exception.detail) 1156 self.assertIn(self.provider.acs_url, ctx.exception.detail)
Test that a mismatched ACS URL is rejected without echoing either URL to the user
1158 def test_malformed_unsigned(self): 1159 """Test that malformed requests to a provider without a verification certificate are 1160 rejected with a handled error instead of a server error""" 1161 self.provider.verification_kp = None 1162 self.provider.save() 1163 missing_id = ( 1164 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1165 'Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1166 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1167 ) 1168 parser = AuthNRequestParser(self.provider) 1169 for payload in ("this is not xml", missing_id): 1170 with self.subTest(payload=payload, binding="post"): 1171 with self.assertRaisesMessage( 1172 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1173 ): 1174 parser.parse(b64encode(payload.encode()).decode()) 1175 with self.subTest(payload=payload, binding="redirect"): 1176 with self.assertRaisesMessage( 1177 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1178 ): 1179 parser.parse_detached(deflate_and_base64_encode(payload), None) 1180 1181 for binding, method in (("post", parser.parse), ("redirect", parser.parse_detached)): 1182 with self.subTest(payload="not base64", binding=binding): 1183 with self.assertRaisesMessage( 1184 CannotHandleAssertion, str(ERROR_CANNOT_DECODE_REQUEST) 1185 ): 1186 method("%%%not-base64%%%", None)
Test that malformed requests to a provider without a verification certificate are rejected with a handled error instead of a server error
1188 def test_redirect_over_size_limit(self): 1189 """Test that a redirect-binding request that inflates beyond the size limit is refused""" 1190 request = deflate_and_base64_encode( 1191 '<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' 1192 'ID="_1" Version="2.0" IssueInstant="2026-05-19T01:01:53.461Z" ' 1193 'AssertionConsumerServiceURL="http://testserver/source/saml/provider/acs/"/>' 1194 + " " * (32 * 1024 * 1024) 1195 ) 1196 1197 tracemalloc.start() 1198 self.addCleanup(tracemalloc.stop) 1199 with self.assertRaises(CannotHandleAssertion): 1200 AuthNRequestParser(self.provider).parse_detached(request, None) 1201 _, peak = tracemalloc.get_traced_memory() 1202 1203 self.assertLess(peak, 32 * 1024 * 1024)
Test that a redirect-binding request that inflates beyond the size limit is refused