authentik.sources.saml.tests.test_response
SAML Source tests
1"""SAML Source tests""" 2 3from base64 import b64encode 4from unittest.mock import MagicMock, patch 5 6from django.test import TestCase 7from freezegun import freeze_time 8 9from authentik.core.models import SourceUserMatchingModes 10from authentik.core.sources.matcher import Action, SourceMatcher 11from authentik.core.tests.utils import ( 12 RequestFactory, 13 create_test_cert, 14 create_test_flow, 15 create_test_user, 16) 17from authentik.crypto.models import CertificateKeyPair 18from authentik.lib.generators import generate_id 19from authentik.lib.tests.utils import load_fixture 20from authentik.sources.saml.exceptions import ( 21 InvalidEncryption, 22 InvalidSignature, 23 MismatchedAudience, 24 UnsuccessfulStatus, 25) 26from authentik.sources.saml.models import ( 27 GroupSAMLSourceConnection, 28 SAMLSource, 29 UserSAMLSourceConnection, 30) 31from authentik.sources.saml.processors.response import ResponseProcessor 32 33DEMO_ACS_URL = "http://sp.example.com/demo1/index.php?acs" 34GOOGLE_ACS_URL = "https://127.0.0.1:9443/source/saml/google/acs/" 35KEYCLOAK_ACS_URL = "http://localhost:9000/source/saml/keycloak/acs/" 36SHIBBOLETH_ACS_URL = "https://sp.example.org:9443/source/saml/shibboleth-post/acs/" 37SHIBBOLETH_TRANSIENT_ACS_URL = "https://sp.example.org:10443/Shibboleth.sso/SAML2/POST" 38 39 40@patch("authentik.sources.saml.processors.response.reverse", MagicMock(return_value=DEMO_ACS_URL)) 41class TestResponseProcessor(TestCase): 42 """Test ResponseProcessor""" 43 44 def setUp(self): 45 self.factory = RequestFactory() 46 self.source = SAMLSource.objects.create( 47 name=generate_id(), 48 slug=generate_id(), 49 issuer_override="http://sp.example.com/demo1/metadata.php", 50 allow_idp_initiated=True, 51 pre_authentication_flow=create_test_flow(), 52 ) 53 54 def test_status_error(self): 55 """Test error status""" 56 request = self.factory.post( 57 "/", 58 data={ 59 "SAMLResponse": b64encode( 60 load_fixture("fixtures/response_error.xml").encode() 61 ).decode() 62 }, 63 ) 64 65 with self.assertRaisesMessage( 66 UnsuccessfulStatus, 67 ( 68 "Invalid request, ACS Url in request http://localhost:9000/source/saml/google/acs/ " 69 "doesn't match configured ACS Url https://127.0.0.1:9443/source/saml/google/acs/." 70 ), 71 ): 72 ResponseProcessor(self.source, request).parse() 73 74 @freeze_time("2022-10-14T14:15:00") 75 def test_success(self): 76 """Test success""" 77 request = self.factory.post( 78 "/", 79 data={ 80 "SAMLResponse": b64encode( 81 load_fixture("fixtures/response_success.xml").encode() 82 ).decode() 83 }, 84 ) 85 86 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 87 parser = ResponseProcessor(self.source, request) 88 with patch( 89 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 90 ): 91 parser.parse() 92 sfm = parser.prepare_flow_manager() 93 self.assertEqual( 94 sfm.user_properties, 95 { 96 "email": "foo@bar.baz", 97 "name": "foo", 98 "sn": "bar", 99 "username": "jens@goauthentik.io", 100 "attributes": {}, 101 "path": self.source.get_user_path(), 102 }, 103 ) 104 105 @freeze_time("2022-10-14T14:15:00") 106 def test_success_no_name_id_format(self): 107 """Test success with a NameID that has no Format attribute""" 108 request = self.factory.post( 109 "/", 110 data={ 111 "SAMLResponse": b64encode( 112 load_fixture("fixtures/response_success_no_nameid_format.xml").encode() 113 ).decode() 114 }, 115 ) 116 117 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 118 with patch( 119 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 120 ): 121 parser = ResponseProcessor(self.source, request) 122 parser.parse() 123 sfm = parser.prepare_flow_manager() 124 self.assertEqual(sfm.user_properties["username"], "jens@goauthentik.io") 125 126 @freeze_time("2022-10-14T14:15:00") 127 def test_audience_mismatch(self): 128 """Test that an assertion whose audience doesn't match our entity ID is rejected""" 129 request = self.factory.post( 130 "/", 131 data={ 132 "SAMLResponse": b64encode( 133 load_fixture("fixtures/response_success.xml").encode() 134 ).decode() 135 }, 136 ) 137 138 parser = ResponseProcessor(self.source, request) 139 with self.assertRaises(MismatchedAudience): 140 parser.parse() 141 142 def _audience_request(self, restrictions: str): 143 """Build a request from the success fixture with its AudienceRestriction replaced""" 144 fixture = load_fixture("fixtures/response_success.xml") 145 start = fixture.index("<saml2:AudienceRestriction>") 146 end = fixture.index("</saml2:AudienceRestriction>") + len("</saml2:AudienceRestriction>") 147 fixture = fixture[:start] + restrictions + fixture[end:] 148 return self.factory.post( 149 "/", 150 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 151 ) 152 153 @freeze_time("2022-10-14T14:15:00") 154 def test_audience_no_restriction(self): 155 """Test that an assertion without any AudienceRestriction is accepted""" 156 request = self._audience_request("") 157 158 parser = ResponseProcessor(self.source, request) 159 with patch( 160 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 161 ): 162 parser.parse() 163 164 @freeze_time("2022-10-14T14:15:00") 165 def test_audience_multiple_in_one_restriction(self): 166 """Test that we are accepted when an AudienceRestriction lists us and another audience""" 167 request = self._audience_request( 168 "<saml2:AudienceRestriction>" 169 "<saml2:Audience>https://other.example.com</saml2:Audience>" 170 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 171 "</saml2:AudienceRestriction>" 172 ) 173 174 parser = ResponseProcessor(self.source, request) 175 with patch( 176 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 177 ): 178 parser.parse() 179 180 @freeze_time("2022-10-14T14:15:00") 181 def test_audience_missing_from_one_restriction(self): 182 """Test that we are rejected when one of several AudienceRestrictions does not list us""" 183 request = self._audience_request( 184 "<saml2:AudienceRestriction>" 185 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 186 "</saml2:AudienceRestriction>" 187 "<saml2:AudienceRestriction>" 188 "<saml2:Audience>https://other.example.com</saml2:Audience>" 189 "</saml2:AudienceRestriction>" 190 ) 191 192 parser = ResponseProcessor(self.source, request) 193 with self.assertRaises(MismatchedAudience): 194 parser.parse() 195 196 @freeze_time("2022-10-14T14:15:00") 197 def test_audience_in_every_restriction(self): 198 """Test that we are accepted when every AudienceRestriction lists us""" 199 request = self._audience_request( 200 "<saml2:AudienceRestriction>" 201 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 202 "<saml2:Audience>https://other.example.com</saml2:Audience>" 203 "</saml2:AudienceRestriction>" 204 "<saml2:AudienceRestriction>" 205 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 206 "</saml2:AudienceRestriction>" 207 ) 208 209 parser = ResponseProcessor(self.source, request) 210 with patch( 211 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 212 ): 213 parser.parse() 214 215 @freeze_time("2022-10-14T14:16:40Z") 216 def test_success_with_status_message_and_detail(self): 217 """Test success with StatusMessage and StatusDetail present (should not raise error)""" 218 request = self.factory.post( 219 "/", 220 data={ 221 "SAMLResponse": b64encode( 222 load_fixture("fixtures/response_success_with_message.xml").encode() 223 ).decode() 224 }, 225 ) 226 227 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 228 parser = ResponseProcessor(self.source, request) 229 with patch( 230 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 231 ): 232 parser.parse() 233 sfm = parser.prepare_flow_manager() 234 self.assertEqual(sfm.user_properties["username"], "jens@goauthentik.io") 235 236 @freeze_time("2022-10-14T14:16:40Z") 237 def test_error_with_message_and_detail(self): 238 """Test error status with StatusMessage and StatusDetail includes both in error""" 239 request = self.factory.post( 240 "/", 241 data={ 242 "SAMLResponse": b64encode( 243 load_fixture("fixtures/response_error_with_detail.xml").encode() 244 ).decode() 245 }, 246 ) 247 248 with self.assertRaises(UnsuccessfulStatus) as ctx: 249 ResponseProcessor(self.source, request).parse() 250 # Should contain both detail and message 251 self.assertIn("User account is disabled", str(ctx.exception)) 252 self.assertIn("Authentication failed", str(ctx.exception)) 253 254 @freeze_time("2024-08-07T15:48:09.325Z") 255 def test_encrypted_correct(self): 256 """Test encrypted""" 257 key = load_fixture("fixtures/encrypted-key.pem") 258 kp = CertificateKeyPair.objects.create( 259 name=generate_id(), 260 key_data=key, 261 ) 262 self.source.encryption_kp = kp 263 request = self.factory.post( 264 "/", 265 data={ 266 "SAMLResponse": b64encode( 267 load_fixture("fixtures/response_encrypted.xml").encode() 268 ).decode() 269 }, 270 ) 271 272 self.source.issuer_override = "authentik-saml-encrypt" 273 parser = ResponseProcessor(self.source, request) 274 with patch( 275 "authentik.sources.saml.processors.response.reverse", return_value=KEYCLOAK_ACS_URL 276 ): 277 parser.parse() 278 279 def test_encrypted_incorrect_key(self): 280 """Test encrypted""" 281 kp = create_test_cert() 282 self.source.encryption_kp = kp 283 request = self.factory.post( 284 "/", 285 data={ 286 "SAMLResponse": b64encode( 287 load_fixture("fixtures/response_encrypted.xml").encode() 288 ).decode() 289 }, 290 ) 291 292 parser = ResponseProcessor(self.source, request) 293 with self.assertRaises(InvalidEncryption): 294 parser.parse() 295 296 @freeze_time("2022-10-14T14:16:40Z") 297 def test_verification_assertion(self): 298 """Test verifying signature inside assertion""" 299 key = load_fixture("fixtures/signature_cert.pem") 300 kp = CertificateKeyPair.objects.create( 301 name=generate_id(), 302 certificate_data=key, 303 ) 304 self.source.verification_kp = kp 305 self.source.signed_assertion = True 306 self.source.signed_response = False 307 request = self.factory.post( 308 "/", 309 data={ 310 "SAMLResponse": b64encode( 311 load_fixture("fixtures/response_signed_assertion.xml").encode() 312 ).decode() 313 }, 314 ) 315 316 parser = ResponseProcessor(self.source, request) 317 parser.parse() 318 319 @freeze_time("2014-07-17T01:02:18Z") 320 def test_verification_assertion_duplicate(self): 321 """Test verifying signature inside assertion, where the response has another assertion 322 before our signed assertion""" 323 key = load_fixture("fixtures/signature_cert.pem") 324 kp = CertificateKeyPair.objects.create( 325 name=generate_id(), 326 certificate_data=key, 327 ) 328 self.source.verification_kp = kp 329 self.source.signed_assertion = True 330 self.source.signed_response = False 331 request = self.factory.post( 332 "/", 333 data={ 334 "SAMLResponse": b64encode( 335 load_fixture("fixtures/response_signed_assertion_dup.xml").encode() 336 ).decode() 337 }, 338 ) 339 340 parser = ResponseProcessor(self.source, request) 341 parser.parse() 342 self.assertNotEqual(parser._get_name_id()[1], "bad") 343 self.assertEqual(parser._get_name_id()[1], "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7") 344 345 @freeze_time("2014-07-17T01:02:18Z") 346 def test_verification_assertion_xsw_nested_duplicate_id(self): 347 """Nested-duplicate-ID XSW: a forged outer Assertion shares its ID with a 348 nested copy of the original signed Assertion (placed inside <saml:Advice>), 349 so the Signature's Reference URI (#ORIG_ID) matches the outer Assertion's 350 ID *and* dereferences to legitimately-signed content. Must be rejected.""" 351 key = load_fixture("fixtures/signature_cert.pem") 352 kp = CertificateKeyPair.objects.create( 353 name=generate_id(), 354 certificate_data=key, 355 ) 356 self.source.verification_kp = kp 357 self.source.signed_assertion = True 358 self.source.signed_response = False 359 request = self.factory.post( 360 "/", 361 data={ 362 "SAMLResponse": b64encode( 363 load_fixture("fixtures/response_signed_assertion_xsw_nested.xml").encode() 364 ).decode() 365 }, 366 ) 367 368 parser = ResponseProcessor(self.source, request) 369 with self.assertRaises(InvalidSignature): 370 parser.parse() 371 372 @freeze_time("2014-07-17T01:02:18Z") 373 def test_verification_response_uri_empty(self): 374 """Some real-world IdPs (notably some Okta dev-tenant configurations 375 observed in the gosaml2 testdata corpus at saml.oktadev.com) sign the 376 Response with ds:Reference URI="" instead of URI="#<ID>". Per xmldsig 377 §4.4.3.2, URI="" covers the entire enclosing document via the 378 enveloped-signature transform — strictly more attested content than 379 "#<ID>" — so consuming the target is a subset of what was signed.""" 380 key = load_fixture("fixtures/signature_cert_uri_empty.pem") 381 kp = CertificateKeyPair.objects.create( 382 name=generate_id(), 383 certificate_data=key, 384 ) 385 self.source.verification_kp = kp 386 self.source.signed_response = True 387 self.source.signed_assertion = False 388 request = self.factory.post( 389 "/", 390 data={ 391 "SAMLResponse": b64encode( 392 load_fixture("fixtures/response_signed_response_uri_empty.xml").encode() 393 ).decode() 394 }, 395 ) 396 397 parser = ResponseProcessor(self.source, request) 398 parser.parse() 399 400 @freeze_time("2014-07-17T01:02:18Z") 401 def test_verification_assertion_uri_empty(self): 402 """Symmetric to test_verification_response_uri_empty but for an 403 Assertion-level signature: the same xmldsig "this document" semantics 404 still cover the whole enclosing document, so the Assertion we then 405 consume is part of the attested content. We have no real-world IdP 406 samples emitting this configuration, but the pre-fix code accepted it 407 and the cryptographic guarantee holds, so keep accepting it rather 408 than risk breaking an IdP we haven't sampled.""" 409 key = load_fixture("fixtures/signature_cert_assertion_uri_empty.pem") 410 kp = CertificateKeyPair.objects.create( 411 name=generate_id(), 412 certificate_data=key, 413 ) 414 self.source.verification_kp = kp 415 self.source.signed_assertion = True 416 self.source.signed_response = False 417 request = self.factory.post( 418 "/", 419 data={ 420 "SAMLResponse": b64encode( 421 load_fixture("fixtures/response_signed_assertion_uri_empty.xml").encode() 422 ).decode() 423 }, 424 ) 425 426 parser = ResponseProcessor(self.source, request) 427 parser.parse() 428 429 @freeze_time("2014-07-17T01:02:18Z") 430 def test_verification_assertion_xsw3(self): 431 """XSW-3 (signature relocation): a forged Assertion contains a Signature whose 432 ds:Reference URI points to a second Assertion in the document. The signature 433 verifies (because the digest matches the legitimate referenced Assertion), 434 but the verifier must NOT then consume the forged Assertion as if it were 435 signed.""" 436 key = load_fixture("fixtures/signature_cert.pem") 437 kp = CertificateKeyPair.objects.create( 438 name=generate_id(), 439 certificate_data=key, 440 ) 441 self.source.verification_kp = kp 442 self.source.signed_assertion = True 443 self.source.signed_response = False 444 request = self.factory.post( 445 "/", 446 data={ 447 "SAMLResponse": b64encode( 448 load_fixture("fixtures/response_signed_assertion_xsw3.xml").encode() 449 ).decode() 450 }, 451 ) 452 453 parser = ResponseProcessor(self.source, request) 454 with self.assertRaises(InvalidSignature): 455 parser.parse() 456 457 @freeze_time("2014-07-17T01:02:18Z") 458 def test_name_id_comment(self): 459 """Test comment in name ID""" 460 fixture = load_fixture("fixtures/response_signed_assertion.xml") 461 fixture = fixture.replace( 462 "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7", 463 "_ce3d2948b4cf20146dee0a0b3dd6f<!--x-->69b6cf86f62d7", 464 ) 465 key = load_fixture("fixtures/signature_cert.pem") 466 kp = CertificateKeyPair.objects.create( 467 name=generate_id(), 468 certificate_data=key, 469 ) 470 self.source.verification_kp = kp 471 self.source.signed_assertion = True 472 self.source.signed_response = False 473 request = self.factory.post( 474 "/", 475 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 476 ) 477 478 parser = ResponseProcessor(self.source, request) 479 parser.parse() 480 self.assertEqual(parser._get_name_id()[1], "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7") 481 482 @freeze_time("2014-07-17T01:02:18Z") 483 def test_name_id_comment_username_truncation(self): 484 """Test that a comment in the NameID does not truncate the matching username. 485 486 The connection identifier reads the full text content with 487 ``"".join(name_id.itertext())``, so the username used for matching must read 488 the same value and not ``name_id.text``, which returns only the text before 489 the first child node.""" 490 full_name_id = "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7" 491 # The text before the comment, which is what ``name_id.text`` returns. 492 truncated_name_id = "_ce3d2948b4cf20146dee0a0b3dd6f" 493 commented_name_id = f"{truncated_name_id}<!--x-->{full_name_id[len(truncated_name_id):]}" 494 fixture = load_fixture("fixtures/response_signed_assertion.xml").replace( 495 full_name_id, commented_name_id 496 ) 497 key = load_fixture("fixtures/signature_cert.pem") 498 kp = CertificateKeyPair.objects.create(name=generate_id(), certificate_data=key) 499 self.source.verification_kp = kp 500 self.source.signed_assertion = True 501 self.source.signed_response = False 502 self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK 503 request = self.factory.post( 504 "/", 505 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 506 ) 507 508 parser = ResponseProcessor(self.source, request) 509 # The comment is dropped by the signature canonicalization, so the signature 510 # still verifies. 511 parser.parse() 512 513 name_id_el, identifier = parser._get_name_id() 514 self.assertEqual(identifier, full_name_id) 515 516 properties = self.source.get_base_user_properties( 517 root=parser._root, assertion=parser.get_assertion(), name_id=name_id_el 518 ) 519 # The username must match the full identifier, not the truncated text. 520 self.assertEqual(properties["username"], identifier) 521 522 # An existing user matching only the truncated text must not be linked. 523 other_user = create_test_user(name=truncated_name_id) 524 matcher = SourceMatcher(self.source, UserSAMLSourceConnection, GroupSAMLSourceConnection) 525 action, connection = matcher.get_user_action(identifier, properties) 526 self.assertEqual(action, Action.ENROLL) 527 self.assertNotEqual(connection.user_id, other_user.pk) 528 529 @freeze_time("2014-07-17T01:02:18Z") 530 def test_attribute_value_comment_truncation(self): 531 """Test that a comment in an attribute value does not truncate it. 532 533 Attribute values feed user matching and property mappings, so a value must 534 be read with ``"".join(value.itertext())`` and not ``value.text``, which 535 returns only the text before the first child node.""" 536 fixture = load_fixture("fixtures/response_signed_assertion.xml").replace( 537 "test@example.com", "test@<!--x-->example.com" 538 ) 539 key = load_fixture("fixtures/signature_cert.pem") 540 kp = CertificateKeyPair.objects.create(name=generate_id(), certificate_data=key) 541 self.source.verification_kp = kp 542 self.source.signed_assertion = True 543 self.source.signed_response = False 544 request = self.factory.post( 545 "/", 546 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 547 ) 548 549 parser = ResponseProcessor(self.source, request) 550 parser.parse() 551 552 name_id_el, _ = parser._get_name_id() 553 properties = self.source.get_base_user_properties( 554 root=parser._root, assertion=parser.get_assertion(), name_id=name_id_el 555 ) 556 # The attribute value must not be truncated at the comment. 557 self.assertEqual(properties["mail"], "test@example.com") 558 559 @freeze_time("2014-07-17T01:02:18Z") 560 def test_verification_response(self): 561 """Test verifying signature inside response""" 562 key = load_fixture("fixtures/signature_cert.pem") 563 kp = CertificateKeyPair.objects.create( 564 name=generate_id(), 565 certificate_data=key, 566 ) 567 self.source.verification_kp = kp 568 self.source.signed_response = True 569 self.source.signed_assertion = False 570 request = self.factory.post( 571 "/", 572 data={ 573 "SAMLResponse": b64encode( 574 load_fixture("fixtures/response_signed_response.xml").encode() 575 ).decode() 576 }, 577 ) 578 579 parser = ResponseProcessor(self.source, request) 580 parser.parse() 581 582 @freeze_time("2024-01-18T06:20:48Z") 583 def test_verification_response_and_assertion(self): 584 """Test verifying signature inside response and assertion""" 585 key = load_fixture("fixtures/signature_cert.pem") 586 kp = CertificateKeyPair.objects.create( 587 name=generate_id(), 588 certificate_data=key, 589 ) 590 self.source.verification_kp = kp 591 self.source.signed_assertion = True 592 self.source.signed_response = True 593 request = self.factory.post( 594 "/", 595 data={ 596 "SAMLResponse": b64encode( 597 load_fixture("fixtures/response_signed_response_and_assertion.xml").encode() 598 ).decode() 599 }, 600 ) 601 602 parser = ResponseProcessor(self.source, request) 603 parser.parse() 604 605 def test_verification_wrong_signature(self): 606 """Test invalid signature fails""" 607 key = load_fixture("fixtures/signature_cert.pem") 608 kp = CertificateKeyPair.objects.create( 609 name=generate_id(), 610 certificate_data=key, 611 ) 612 self.source.verification_kp = kp 613 self.source.signed_assertion = True 614 request = self.factory.post( 615 "/", 616 data={ 617 "SAMLResponse": b64encode( 618 # Same as response_signed_assertion.xml but the role name is altered 619 load_fixture("fixtures/response_signed_error.xml").encode() 620 ).decode() 621 }, 622 ) 623 624 parser = ResponseProcessor(self.source, request) 625 626 with self.assertRaisesMessage(InvalidSignature, ""): 627 parser.parse() 628 629 @freeze_time("2022-10-14T14:15:00") 630 def test_verification_no_signature(self): 631 """Test rejecting response without signature when signed_assertion is True""" 632 key = load_fixture("fixtures/signature_cert.pem") 633 kp = CertificateKeyPair.objects.create( 634 name=generate_id(), 635 certificate_data=key, 636 ) 637 self.source.verification_kp = kp 638 self.source.signed_assertion = True 639 request = self.factory.post( 640 "/", 641 data={ 642 "SAMLResponse": b64encode( 643 load_fixture("fixtures/response_success.xml").encode() 644 ).decode() 645 }, 646 ) 647 648 parser = ResponseProcessor(self.source, request) 649 650 with self.assertRaisesMessage(InvalidSignature, ""): 651 parser.parse() 652 653 def test_verification_incorrect_response(self): 654 """Test verifying signature inside response""" 655 key = load_fixture("fixtures/signature_cert.pem") 656 kp = CertificateKeyPair.objects.create( 657 name=generate_id(), 658 certificate_data=key, 659 ) 660 self.source.verification_kp = kp 661 self.source.signed_response = True 662 self.source.signed_assertion = False 663 request = self.factory.post( 664 "/", 665 data={ 666 "SAMLResponse": b64encode( 667 load_fixture("fixtures/response_incorrect_signed_response.xml").encode() 668 ).decode() 669 }, 670 ) 671 672 parser = ResponseProcessor(self.source, request) 673 with self.assertRaisesMessage(InvalidSignature, ""): 674 parser.parse() 675 676 @freeze_time("2025-10-30T05:45:47.619Z") 677 def test_signed_encrypted_response(self): 678 """Test signed & encrypted response""" 679 verification_key = load_fixture("fixtures/signature_cert2.pem") 680 vkp = CertificateKeyPair.objects.create( 681 name=generate_id(), 682 certificate_data=verification_key, 683 ) 684 685 encrypted_key = load_fixture("fixtures/encrypted-key2.pem") 686 ekp = CertificateKeyPair.objects.create(name=generate_id(), key_data=encrypted_key) 687 688 self.source.verification_kp = vkp 689 self.source.encryption_kp = ekp 690 self.source.signed_response = True 691 self.source.signed_assertion = False 692 request = self.factory.post( 693 "/", 694 data={ 695 "SAMLResponse": b64encode( 696 load_fixture("fixtures/response_signed_encrypted.xml").encode() 697 ).decode() 698 }, 699 ) 700 701 self.source.issuer_override = "https://sp.example.org/shibboleth/POST" 702 parser = ResponseProcessor(self.source, request) 703 with patch( 704 "authentik.sources.saml.processors.response.reverse", return_value=SHIBBOLETH_ACS_URL 705 ): 706 parser.parse() 707 708 @freeze_time("2026-01-21T14:23") 709 def test_transient(self): 710 """Test SAML transient NameID""" 711 verification_key = load_fixture("fixtures/signature_cert2.pem") 712 vkp = CertificateKeyPair.objects.create( 713 name=generate_id(), 714 certificate_data=verification_key, 715 ) 716 self.source.verification_kp = vkp 717 self.source.signed_response = True 718 self.source.signed_assertion = False 719 request = self.factory.post( 720 "/", 721 data={ 722 "SAMLResponse": b64encode( 723 load_fixture("fixtures/response_transient.xml").encode() 724 ).decode() 725 }, 726 ) 727 728 self.source.issuer_override = "https://sp.example.org/shibboleth" 729 parser = ResponseProcessor(self.source, request) 730 with patch( 731 "authentik.sources.saml.processors.response.reverse", 732 return_value=SHIBBOLETH_TRANSIENT_ACS_URL, 733 ): 734 parser.parse() 735 parser.prepare_flow_manager() 736 737 def test_doctype(self): 738 """Test that a Response with a document type declaration is refused""" 739 response = load_fixture("fixtures/response_success.xml").replace( 740 '<?xml version="1.0" encoding="UTF-8" standalone="no"?>', 741 '<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE saml2p:Response>', 742 ) 743 request = self.factory.post( 744 "/", 745 data={"SAMLResponse": b64encode(response.encode()).decode()}, 746 ) 747 748 with self.assertRaisesMessage(ValueError, "XML document contains a DOCTYPE declaration"): 749 ResponseProcessor(self.source, request).parse()
41@patch("authentik.sources.saml.processors.response.reverse", MagicMock(return_value=DEMO_ACS_URL)) 42class TestResponseProcessor(TestCase): 43 """Test ResponseProcessor""" 44 45 def setUp(self): 46 self.factory = RequestFactory() 47 self.source = SAMLSource.objects.create( 48 name=generate_id(), 49 slug=generate_id(), 50 issuer_override="http://sp.example.com/demo1/metadata.php", 51 allow_idp_initiated=True, 52 pre_authentication_flow=create_test_flow(), 53 ) 54 55 def test_status_error(self): 56 """Test error status""" 57 request = self.factory.post( 58 "/", 59 data={ 60 "SAMLResponse": b64encode( 61 load_fixture("fixtures/response_error.xml").encode() 62 ).decode() 63 }, 64 ) 65 66 with self.assertRaisesMessage( 67 UnsuccessfulStatus, 68 ( 69 "Invalid request, ACS Url in request http://localhost:9000/source/saml/google/acs/ " 70 "doesn't match configured ACS Url https://127.0.0.1:9443/source/saml/google/acs/." 71 ), 72 ): 73 ResponseProcessor(self.source, request).parse() 74 75 @freeze_time("2022-10-14T14:15:00") 76 def test_success(self): 77 """Test success""" 78 request = self.factory.post( 79 "/", 80 data={ 81 "SAMLResponse": b64encode( 82 load_fixture("fixtures/response_success.xml").encode() 83 ).decode() 84 }, 85 ) 86 87 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 88 parser = ResponseProcessor(self.source, request) 89 with patch( 90 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 91 ): 92 parser.parse() 93 sfm = parser.prepare_flow_manager() 94 self.assertEqual( 95 sfm.user_properties, 96 { 97 "email": "foo@bar.baz", 98 "name": "foo", 99 "sn": "bar", 100 "username": "jens@goauthentik.io", 101 "attributes": {}, 102 "path": self.source.get_user_path(), 103 }, 104 ) 105 106 @freeze_time("2022-10-14T14:15:00") 107 def test_success_no_name_id_format(self): 108 """Test success with a NameID that has no Format attribute""" 109 request = self.factory.post( 110 "/", 111 data={ 112 "SAMLResponse": b64encode( 113 load_fixture("fixtures/response_success_no_nameid_format.xml").encode() 114 ).decode() 115 }, 116 ) 117 118 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 119 with patch( 120 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 121 ): 122 parser = ResponseProcessor(self.source, request) 123 parser.parse() 124 sfm = parser.prepare_flow_manager() 125 self.assertEqual(sfm.user_properties["username"], "jens@goauthentik.io") 126 127 @freeze_time("2022-10-14T14:15:00") 128 def test_audience_mismatch(self): 129 """Test that an assertion whose audience doesn't match our entity ID is rejected""" 130 request = self.factory.post( 131 "/", 132 data={ 133 "SAMLResponse": b64encode( 134 load_fixture("fixtures/response_success.xml").encode() 135 ).decode() 136 }, 137 ) 138 139 parser = ResponseProcessor(self.source, request) 140 with self.assertRaises(MismatchedAudience): 141 parser.parse() 142 143 def _audience_request(self, restrictions: str): 144 """Build a request from the success fixture with its AudienceRestriction replaced""" 145 fixture = load_fixture("fixtures/response_success.xml") 146 start = fixture.index("<saml2:AudienceRestriction>") 147 end = fixture.index("</saml2:AudienceRestriction>") + len("</saml2:AudienceRestriction>") 148 fixture = fixture[:start] + restrictions + fixture[end:] 149 return self.factory.post( 150 "/", 151 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 152 ) 153 154 @freeze_time("2022-10-14T14:15:00") 155 def test_audience_no_restriction(self): 156 """Test that an assertion without any AudienceRestriction is accepted""" 157 request = self._audience_request("") 158 159 parser = ResponseProcessor(self.source, request) 160 with patch( 161 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 162 ): 163 parser.parse() 164 165 @freeze_time("2022-10-14T14:15:00") 166 def test_audience_multiple_in_one_restriction(self): 167 """Test that we are accepted when an AudienceRestriction lists us and another audience""" 168 request = self._audience_request( 169 "<saml2:AudienceRestriction>" 170 "<saml2:Audience>https://other.example.com</saml2:Audience>" 171 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 172 "</saml2:AudienceRestriction>" 173 ) 174 175 parser = ResponseProcessor(self.source, request) 176 with patch( 177 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 178 ): 179 parser.parse() 180 181 @freeze_time("2022-10-14T14:15:00") 182 def test_audience_missing_from_one_restriction(self): 183 """Test that we are rejected when one of several AudienceRestrictions does not list us""" 184 request = self._audience_request( 185 "<saml2:AudienceRestriction>" 186 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 187 "</saml2:AudienceRestriction>" 188 "<saml2:AudienceRestriction>" 189 "<saml2:Audience>https://other.example.com</saml2:Audience>" 190 "</saml2:AudienceRestriction>" 191 ) 192 193 parser = ResponseProcessor(self.source, request) 194 with self.assertRaises(MismatchedAudience): 195 parser.parse() 196 197 @freeze_time("2022-10-14T14:15:00") 198 def test_audience_in_every_restriction(self): 199 """Test that we are accepted when every AudienceRestriction lists us""" 200 request = self._audience_request( 201 "<saml2:AudienceRestriction>" 202 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 203 "<saml2:Audience>https://other.example.com</saml2:Audience>" 204 "</saml2:AudienceRestriction>" 205 "<saml2:AudienceRestriction>" 206 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 207 "</saml2:AudienceRestriction>" 208 ) 209 210 parser = ResponseProcessor(self.source, request) 211 with patch( 212 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 213 ): 214 parser.parse() 215 216 @freeze_time("2022-10-14T14:16:40Z") 217 def test_success_with_status_message_and_detail(self): 218 """Test success with StatusMessage and StatusDetail present (should not raise error)""" 219 request = self.factory.post( 220 "/", 221 data={ 222 "SAMLResponse": b64encode( 223 load_fixture("fixtures/response_success_with_message.xml").encode() 224 ).decode() 225 }, 226 ) 227 228 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 229 parser = ResponseProcessor(self.source, request) 230 with patch( 231 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 232 ): 233 parser.parse() 234 sfm = parser.prepare_flow_manager() 235 self.assertEqual(sfm.user_properties["username"], "jens@goauthentik.io") 236 237 @freeze_time("2022-10-14T14:16:40Z") 238 def test_error_with_message_and_detail(self): 239 """Test error status with StatusMessage and StatusDetail includes both in error""" 240 request = self.factory.post( 241 "/", 242 data={ 243 "SAMLResponse": b64encode( 244 load_fixture("fixtures/response_error_with_detail.xml").encode() 245 ).decode() 246 }, 247 ) 248 249 with self.assertRaises(UnsuccessfulStatus) as ctx: 250 ResponseProcessor(self.source, request).parse() 251 # Should contain both detail and message 252 self.assertIn("User account is disabled", str(ctx.exception)) 253 self.assertIn("Authentication failed", str(ctx.exception)) 254 255 @freeze_time("2024-08-07T15:48:09.325Z") 256 def test_encrypted_correct(self): 257 """Test encrypted""" 258 key = load_fixture("fixtures/encrypted-key.pem") 259 kp = CertificateKeyPair.objects.create( 260 name=generate_id(), 261 key_data=key, 262 ) 263 self.source.encryption_kp = kp 264 request = self.factory.post( 265 "/", 266 data={ 267 "SAMLResponse": b64encode( 268 load_fixture("fixtures/response_encrypted.xml").encode() 269 ).decode() 270 }, 271 ) 272 273 self.source.issuer_override = "authentik-saml-encrypt" 274 parser = ResponseProcessor(self.source, request) 275 with patch( 276 "authentik.sources.saml.processors.response.reverse", return_value=KEYCLOAK_ACS_URL 277 ): 278 parser.parse() 279 280 def test_encrypted_incorrect_key(self): 281 """Test encrypted""" 282 kp = create_test_cert() 283 self.source.encryption_kp = kp 284 request = self.factory.post( 285 "/", 286 data={ 287 "SAMLResponse": b64encode( 288 load_fixture("fixtures/response_encrypted.xml").encode() 289 ).decode() 290 }, 291 ) 292 293 parser = ResponseProcessor(self.source, request) 294 with self.assertRaises(InvalidEncryption): 295 parser.parse() 296 297 @freeze_time("2022-10-14T14:16:40Z") 298 def test_verification_assertion(self): 299 """Test verifying signature inside assertion""" 300 key = load_fixture("fixtures/signature_cert.pem") 301 kp = CertificateKeyPair.objects.create( 302 name=generate_id(), 303 certificate_data=key, 304 ) 305 self.source.verification_kp = kp 306 self.source.signed_assertion = True 307 self.source.signed_response = False 308 request = self.factory.post( 309 "/", 310 data={ 311 "SAMLResponse": b64encode( 312 load_fixture("fixtures/response_signed_assertion.xml").encode() 313 ).decode() 314 }, 315 ) 316 317 parser = ResponseProcessor(self.source, request) 318 parser.parse() 319 320 @freeze_time("2014-07-17T01:02:18Z") 321 def test_verification_assertion_duplicate(self): 322 """Test verifying signature inside assertion, where the response has another assertion 323 before our signed assertion""" 324 key = load_fixture("fixtures/signature_cert.pem") 325 kp = CertificateKeyPair.objects.create( 326 name=generate_id(), 327 certificate_data=key, 328 ) 329 self.source.verification_kp = kp 330 self.source.signed_assertion = True 331 self.source.signed_response = False 332 request = self.factory.post( 333 "/", 334 data={ 335 "SAMLResponse": b64encode( 336 load_fixture("fixtures/response_signed_assertion_dup.xml").encode() 337 ).decode() 338 }, 339 ) 340 341 parser = ResponseProcessor(self.source, request) 342 parser.parse() 343 self.assertNotEqual(parser._get_name_id()[1], "bad") 344 self.assertEqual(parser._get_name_id()[1], "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7") 345 346 @freeze_time("2014-07-17T01:02:18Z") 347 def test_verification_assertion_xsw_nested_duplicate_id(self): 348 """Nested-duplicate-ID XSW: a forged outer Assertion shares its ID with a 349 nested copy of the original signed Assertion (placed inside <saml:Advice>), 350 so the Signature's Reference URI (#ORIG_ID) matches the outer Assertion's 351 ID *and* dereferences to legitimately-signed content. Must be rejected.""" 352 key = load_fixture("fixtures/signature_cert.pem") 353 kp = CertificateKeyPair.objects.create( 354 name=generate_id(), 355 certificate_data=key, 356 ) 357 self.source.verification_kp = kp 358 self.source.signed_assertion = True 359 self.source.signed_response = False 360 request = self.factory.post( 361 "/", 362 data={ 363 "SAMLResponse": b64encode( 364 load_fixture("fixtures/response_signed_assertion_xsw_nested.xml").encode() 365 ).decode() 366 }, 367 ) 368 369 parser = ResponseProcessor(self.source, request) 370 with self.assertRaises(InvalidSignature): 371 parser.parse() 372 373 @freeze_time("2014-07-17T01:02:18Z") 374 def test_verification_response_uri_empty(self): 375 """Some real-world IdPs (notably some Okta dev-tenant configurations 376 observed in the gosaml2 testdata corpus at saml.oktadev.com) sign the 377 Response with ds:Reference URI="" instead of URI="#<ID>". Per xmldsig 378 §4.4.3.2, URI="" covers the entire enclosing document via the 379 enveloped-signature transform — strictly more attested content than 380 "#<ID>" — so consuming the target is a subset of what was signed.""" 381 key = load_fixture("fixtures/signature_cert_uri_empty.pem") 382 kp = CertificateKeyPair.objects.create( 383 name=generate_id(), 384 certificate_data=key, 385 ) 386 self.source.verification_kp = kp 387 self.source.signed_response = True 388 self.source.signed_assertion = False 389 request = self.factory.post( 390 "/", 391 data={ 392 "SAMLResponse": b64encode( 393 load_fixture("fixtures/response_signed_response_uri_empty.xml").encode() 394 ).decode() 395 }, 396 ) 397 398 parser = ResponseProcessor(self.source, request) 399 parser.parse() 400 401 @freeze_time("2014-07-17T01:02:18Z") 402 def test_verification_assertion_uri_empty(self): 403 """Symmetric to test_verification_response_uri_empty but for an 404 Assertion-level signature: the same xmldsig "this document" semantics 405 still cover the whole enclosing document, so the Assertion we then 406 consume is part of the attested content. We have no real-world IdP 407 samples emitting this configuration, but the pre-fix code accepted it 408 and the cryptographic guarantee holds, so keep accepting it rather 409 than risk breaking an IdP we haven't sampled.""" 410 key = load_fixture("fixtures/signature_cert_assertion_uri_empty.pem") 411 kp = CertificateKeyPair.objects.create( 412 name=generate_id(), 413 certificate_data=key, 414 ) 415 self.source.verification_kp = kp 416 self.source.signed_assertion = True 417 self.source.signed_response = False 418 request = self.factory.post( 419 "/", 420 data={ 421 "SAMLResponse": b64encode( 422 load_fixture("fixtures/response_signed_assertion_uri_empty.xml").encode() 423 ).decode() 424 }, 425 ) 426 427 parser = ResponseProcessor(self.source, request) 428 parser.parse() 429 430 @freeze_time("2014-07-17T01:02:18Z") 431 def test_verification_assertion_xsw3(self): 432 """XSW-3 (signature relocation): a forged Assertion contains a Signature whose 433 ds:Reference URI points to a second Assertion in the document. The signature 434 verifies (because the digest matches the legitimate referenced Assertion), 435 but the verifier must NOT then consume the forged Assertion as if it were 436 signed.""" 437 key = load_fixture("fixtures/signature_cert.pem") 438 kp = CertificateKeyPair.objects.create( 439 name=generate_id(), 440 certificate_data=key, 441 ) 442 self.source.verification_kp = kp 443 self.source.signed_assertion = True 444 self.source.signed_response = False 445 request = self.factory.post( 446 "/", 447 data={ 448 "SAMLResponse": b64encode( 449 load_fixture("fixtures/response_signed_assertion_xsw3.xml").encode() 450 ).decode() 451 }, 452 ) 453 454 parser = ResponseProcessor(self.source, request) 455 with self.assertRaises(InvalidSignature): 456 parser.parse() 457 458 @freeze_time("2014-07-17T01:02:18Z") 459 def test_name_id_comment(self): 460 """Test comment in name ID""" 461 fixture = load_fixture("fixtures/response_signed_assertion.xml") 462 fixture = fixture.replace( 463 "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7", 464 "_ce3d2948b4cf20146dee0a0b3dd6f<!--x-->69b6cf86f62d7", 465 ) 466 key = load_fixture("fixtures/signature_cert.pem") 467 kp = CertificateKeyPair.objects.create( 468 name=generate_id(), 469 certificate_data=key, 470 ) 471 self.source.verification_kp = kp 472 self.source.signed_assertion = True 473 self.source.signed_response = False 474 request = self.factory.post( 475 "/", 476 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 477 ) 478 479 parser = ResponseProcessor(self.source, request) 480 parser.parse() 481 self.assertEqual(parser._get_name_id()[1], "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7") 482 483 @freeze_time("2014-07-17T01:02:18Z") 484 def test_name_id_comment_username_truncation(self): 485 """Test that a comment in the NameID does not truncate the matching username. 486 487 The connection identifier reads the full text content with 488 ``"".join(name_id.itertext())``, so the username used for matching must read 489 the same value and not ``name_id.text``, which returns only the text before 490 the first child node.""" 491 full_name_id = "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7" 492 # The text before the comment, which is what ``name_id.text`` returns. 493 truncated_name_id = "_ce3d2948b4cf20146dee0a0b3dd6f" 494 commented_name_id = f"{truncated_name_id}<!--x-->{full_name_id[len(truncated_name_id):]}" 495 fixture = load_fixture("fixtures/response_signed_assertion.xml").replace( 496 full_name_id, commented_name_id 497 ) 498 key = load_fixture("fixtures/signature_cert.pem") 499 kp = CertificateKeyPair.objects.create(name=generate_id(), certificate_data=key) 500 self.source.verification_kp = kp 501 self.source.signed_assertion = True 502 self.source.signed_response = False 503 self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK 504 request = self.factory.post( 505 "/", 506 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 507 ) 508 509 parser = ResponseProcessor(self.source, request) 510 # The comment is dropped by the signature canonicalization, so the signature 511 # still verifies. 512 parser.parse() 513 514 name_id_el, identifier = parser._get_name_id() 515 self.assertEqual(identifier, full_name_id) 516 517 properties = self.source.get_base_user_properties( 518 root=parser._root, assertion=parser.get_assertion(), name_id=name_id_el 519 ) 520 # The username must match the full identifier, not the truncated text. 521 self.assertEqual(properties["username"], identifier) 522 523 # An existing user matching only the truncated text must not be linked. 524 other_user = create_test_user(name=truncated_name_id) 525 matcher = SourceMatcher(self.source, UserSAMLSourceConnection, GroupSAMLSourceConnection) 526 action, connection = matcher.get_user_action(identifier, properties) 527 self.assertEqual(action, Action.ENROLL) 528 self.assertNotEqual(connection.user_id, other_user.pk) 529 530 @freeze_time("2014-07-17T01:02:18Z") 531 def test_attribute_value_comment_truncation(self): 532 """Test that a comment in an attribute value does not truncate it. 533 534 Attribute values feed user matching and property mappings, so a value must 535 be read with ``"".join(value.itertext())`` and not ``value.text``, which 536 returns only the text before the first child node.""" 537 fixture = load_fixture("fixtures/response_signed_assertion.xml").replace( 538 "test@example.com", "test@<!--x-->example.com" 539 ) 540 key = load_fixture("fixtures/signature_cert.pem") 541 kp = CertificateKeyPair.objects.create(name=generate_id(), certificate_data=key) 542 self.source.verification_kp = kp 543 self.source.signed_assertion = True 544 self.source.signed_response = False 545 request = self.factory.post( 546 "/", 547 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 548 ) 549 550 parser = ResponseProcessor(self.source, request) 551 parser.parse() 552 553 name_id_el, _ = parser._get_name_id() 554 properties = self.source.get_base_user_properties( 555 root=parser._root, assertion=parser.get_assertion(), name_id=name_id_el 556 ) 557 # The attribute value must not be truncated at the comment. 558 self.assertEqual(properties["mail"], "test@example.com") 559 560 @freeze_time("2014-07-17T01:02:18Z") 561 def test_verification_response(self): 562 """Test verifying signature inside response""" 563 key = load_fixture("fixtures/signature_cert.pem") 564 kp = CertificateKeyPair.objects.create( 565 name=generate_id(), 566 certificate_data=key, 567 ) 568 self.source.verification_kp = kp 569 self.source.signed_response = True 570 self.source.signed_assertion = False 571 request = self.factory.post( 572 "/", 573 data={ 574 "SAMLResponse": b64encode( 575 load_fixture("fixtures/response_signed_response.xml").encode() 576 ).decode() 577 }, 578 ) 579 580 parser = ResponseProcessor(self.source, request) 581 parser.parse() 582 583 @freeze_time("2024-01-18T06:20:48Z") 584 def test_verification_response_and_assertion(self): 585 """Test verifying signature inside response and assertion""" 586 key = load_fixture("fixtures/signature_cert.pem") 587 kp = CertificateKeyPair.objects.create( 588 name=generate_id(), 589 certificate_data=key, 590 ) 591 self.source.verification_kp = kp 592 self.source.signed_assertion = True 593 self.source.signed_response = True 594 request = self.factory.post( 595 "/", 596 data={ 597 "SAMLResponse": b64encode( 598 load_fixture("fixtures/response_signed_response_and_assertion.xml").encode() 599 ).decode() 600 }, 601 ) 602 603 parser = ResponseProcessor(self.source, request) 604 parser.parse() 605 606 def test_verification_wrong_signature(self): 607 """Test invalid signature fails""" 608 key = load_fixture("fixtures/signature_cert.pem") 609 kp = CertificateKeyPair.objects.create( 610 name=generate_id(), 611 certificate_data=key, 612 ) 613 self.source.verification_kp = kp 614 self.source.signed_assertion = True 615 request = self.factory.post( 616 "/", 617 data={ 618 "SAMLResponse": b64encode( 619 # Same as response_signed_assertion.xml but the role name is altered 620 load_fixture("fixtures/response_signed_error.xml").encode() 621 ).decode() 622 }, 623 ) 624 625 parser = ResponseProcessor(self.source, request) 626 627 with self.assertRaisesMessage(InvalidSignature, ""): 628 parser.parse() 629 630 @freeze_time("2022-10-14T14:15:00") 631 def test_verification_no_signature(self): 632 """Test rejecting response without signature when signed_assertion is True""" 633 key = load_fixture("fixtures/signature_cert.pem") 634 kp = CertificateKeyPair.objects.create( 635 name=generate_id(), 636 certificate_data=key, 637 ) 638 self.source.verification_kp = kp 639 self.source.signed_assertion = True 640 request = self.factory.post( 641 "/", 642 data={ 643 "SAMLResponse": b64encode( 644 load_fixture("fixtures/response_success.xml").encode() 645 ).decode() 646 }, 647 ) 648 649 parser = ResponseProcessor(self.source, request) 650 651 with self.assertRaisesMessage(InvalidSignature, ""): 652 parser.parse() 653 654 def test_verification_incorrect_response(self): 655 """Test verifying signature inside response""" 656 key = load_fixture("fixtures/signature_cert.pem") 657 kp = CertificateKeyPair.objects.create( 658 name=generate_id(), 659 certificate_data=key, 660 ) 661 self.source.verification_kp = kp 662 self.source.signed_response = True 663 self.source.signed_assertion = False 664 request = self.factory.post( 665 "/", 666 data={ 667 "SAMLResponse": b64encode( 668 load_fixture("fixtures/response_incorrect_signed_response.xml").encode() 669 ).decode() 670 }, 671 ) 672 673 parser = ResponseProcessor(self.source, request) 674 with self.assertRaisesMessage(InvalidSignature, ""): 675 parser.parse() 676 677 @freeze_time("2025-10-30T05:45:47.619Z") 678 def test_signed_encrypted_response(self): 679 """Test signed & encrypted response""" 680 verification_key = load_fixture("fixtures/signature_cert2.pem") 681 vkp = CertificateKeyPair.objects.create( 682 name=generate_id(), 683 certificate_data=verification_key, 684 ) 685 686 encrypted_key = load_fixture("fixtures/encrypted-key2.pem") 687 ekp = CertificateKeyPair.objects.create(name=generate_id(), key_data=encrypted_key) 688 689 self.source.verification_kp = vkp 690 self.source.encryption_kp = ekp 691 self.source.signed_response = True 692 self.source.signed_assertion = False 693 request = self.factory.post( 694 "/", 695 data={ 696 "SAMLResponse": b64encode( 697 load_fixture("fixtures/response_signed_encrypted.xml").encode() 698 ).decode() 699 }, 700 ) 701 702 self.source.issuer_override = "https://sp.example.org/shibboleth/POST" 703 parser = ResponseProcessor(self.source, request) 704 with patch( 705 "authentik.sources.saml.processors.response.reverse", return_value=SHIBBOLETH_ACS_URL 706 ): 707 parser.parse() 708 709 @freeze_time("2026-01-21T14:23") 710 def test_transient(self): 711 """Test SAML transient NameID""" 712 verification_key = load_fixture("fixtures/signature_cert2.pem") 713 vkp = CertificateKeyPair.objects.create( 714 name=generate_id(), 715 certificate_data=verification_key, 716 ) 717 self.source.verification_kp = vkp 718 self.source.signed_response = True 719 self.source.signed_assertion = False 720 request = self.factory.post( 721 "/", 722 data={ 723 "SAMLResponse": b64encode( 724 load_fixture("fixtures/response_transient.xml").encode() 725 ).decode() 726 }, 727 ) 728 729 self.source.issuer_override = "https://sp.example.org/shibboleth" 730 parser = ResponseProcessor(self.source, request) 731 with patch( 732 "authentik.sources.saml.processors.response.reverse", 733 return_value=SHIBBOLETH_TRANSIENT_ACS_URL, 734 ): 735 parser.parse() 736 parser.prepare_flow_manager() 737 738 def test_doctype(self): 739 """Test that a Response with a document type declaration is refused""" 740 response = load_fixture("fixtures/response_success.xml").replace( 741 '<?xml version="1.0" encoding="UTF-8" standalone="no"?>', 742 '<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE saml2p:Response>', 743 ) 744 request = self.factory.post( 745 "/", 746 data={"SAMLResponse": b64encode(response.encode()).decode()}, 747 ) 748 749 with self.assertRaisesMessage(ValueError, "XML document contains a DOCTYPE declaration"): 750 ResponseProcessor(self.source, request).parse()
Test ResponseProcessor
45 def setUp(self): 46 self.factory = RequestFactory() 47 self.source = SAMLSource.objects.create( 48 name=generate_id(), 49 slug=generate_id(), 50 issuer_override="http://sp.example.com/demo1/metadata.php", 51 allow_idp_initiated=True, 52 pre_authentication_flow=create_test_flow(), 53 )
Hook method for setting up the test fixture before exercising it.
55 def test_status_error(self): 56 """Test error status""" 57 request = self.factory.post( 58 "/", 59 data={ 60 "SAMLResponse": b64encode( 61 load_fixture("fixtures/response_error.xml").encode() 62 ).decode() 63 }, 64 ) 65 66 with self.assertRaisesMessage( 67 UnsuccessfulStatus, 68 ( 69 "Invalid request, ACS Url in request http://localhost:9000/source/saml/google/acs/ " 70 "doesn't match configured ACS Url https://127.0.0.1:9443/source/saml/google/acs/." 71 ), 72 ): 73 ResponseProcessor(self.source, request).parse()
Test error status
75 @freeze_time("2022-10-14T14:15:00") 76 def test_success(self): 77 """Test success""" 78 request = self.factory.post( 79 "/", 80 data={ 81 "SAMLResponse": b64encode( 82 load_fixture("fixtures/response_success.xml").encode() 83 ).decode() 84 }, 85 ) 86 87 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 88 parser = ResponseProcessor(self.source, request) 89 with patch( 90 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 91 ): 92 parser.parse() 93 sfm = parser.prepare_flow_manager() 94 self.assertEqual( 95 sfm.user_properties, 96 { 97 "email": "foo@bar.baz", 98 "name": "foo", 99 "sn": "bar", 100 "username": "jens@goauthentik.io", 101 "attributes": {}, 102 "path": self.source.get_user_path(), 103 }, 104 )
Test success
106 @freeze_time("2022-10-14T14:15:00") 107 def test_success_no_name_id_format(self): 108 """Test success with a NameID that has no Format attribute""" 109 request = self.factory.post( 110 "/", 111 data={ 112 "SAMLResponse": b64encode( 113 load_fixture("fixtures/response_success_no_nameid_format.xml").encode() 114 ).decode() 115 }, 116 ) 117 118 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 119 with patch( 120 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 121 ): 122 parser = ResponseProcessor(self.source, request) 123 parser.parse() 124 sfm = parser.prepare_flow_manager() 125 self.assertEqual(sfm.user_properties["username"], "jens@goauthentik.io")
Test success with a NameID that has no Format attribute
127 @freeze_time("2022-10-14T14:15:00") 128 def test_audience_mismatch(self): 129 """Test that an assertion whose audience doesn't match our entity ID is rejected""" 130 request = self.factory.post( 131 "/", 132 data={ 133 "SAMLResponse": b64encode( 134 load_fixture("fixtures/response_success.xml").encode() 135 ).decode() 136 }, 137 ) 138 139 parser = ResponseProcessor(self.source, request) 140 with self.assertRaises(MismatchedAudience): 141 parser.parse()
Test that an assertion whose audience doesn't match our entity ID is rejected
154 @freeze_time("2022-10-14T14:15:00") 155 def test_audience_no_restriction(self): 156 """Test that an assertion without any AudienceRestriction is accepted""" 157 request = self._audience_request("") 158 159 parser = ResponseProcessor(self.source, request) 160 with patch( 161 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 162 ): 163 parser.parse()
Test that an assertion without any AudienceRestriction is accepted
165 @freeze_time("2022-10-14T14:15:00") 166 def test_audience_multiple_in_one_restriction(self): 167 """Test that we are accepted when an AudienceRestriction lists us and another audience""" 168 request = self._audience_request( 169 "<saml2:AudienceRestriction>" 170 "<saml2:Audience>https://other.example.com</saml2:Audience>" 171 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 172 "</saml2:AudienceRestriction>" 173 ) 174 175 parser = ResponseProcessor(self.source, request) 176 with patch( 177 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 178 ): 179 parser.parse()
Test that we are accepted when an AudienceRestriction lists us and another audience
181 @freeze_time("2022-10-14T14:15:00") 182 def test_audience_missing_from_one_restriction(self): 183 """Test that we are rejected when one of several AudienceRestrictions does not list us""" 184 request = self._audience_request( 185 "<saml2:AudienceRestriction>" 186 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 187 "</saml2:AudienceRestriction>" 188 "<saml2:AudienceRestriction>" 189 "<saml2:Audience>https://other.example.com</saml2:Audience>" 190 "</saml2:AudienceRestriction>" 191 ) 192 193 parser = ResponseProcessor(self.source, request) 194 with self.assertRaises(MismatchedAudience): 195 parser.parse()
Test that we are rejected when one of several AudienceRestrictions does not list us
197 @freeze_time("2022-10-14T14:15:00") 198 def test_audience_in_every_restriction(self): 199 """Test that we are accepted when every AudienceRestriction lists us""" 200 request = self._audience_request( 201 "<saml2:AudienceRestriction>" 202 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 203 "<saml2:Audience>https://other.example.com</saml2:Audience>" 204 "</saml2:AudienceRestriction>" 205 "<saml2:AudienceRestriction>" 206 f"<saml2:Audience>{self.source.issuer_override}</saml2:Audience>" 207 "</saml2:AudienceRestriction>" 208 ) 209 210 parser = ResponseProcessor(self.source, request) 211 with patch( 212 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 213 ): 214 parser.parse()
Test that we are accepted when every AudienceRestriction lists us
216 @freeze_time("2022-10-14T14:16:40Z") 217 def test_success_with_status_message_and_detail(self): 218 """Test success with StatusMessage and StatusDetail present (should not raise error)""" 219 request = self.factory.post( 220 "/", 221 data={ 222 "SAMLResponse": b64encode( 223 load_fixture("fixtures/response_success_with_message.xml").encode() 224 ).decode() 225 }, 226 ) 227 228 self.source.issuer_override = "https://accounts.google.com/o/saml2?idpid=" 229 parser = ResponseProcessor(self.source, request) 230 with patch( 231 "authentik.sources.saml.processors.response.reverse", return_value=GOOGLE_ACS_URL 232 ): 233 parser.parse() 234 sfm = parser.prepare_flow_manager() 235 self.assertEqual(sfm.user_properties["username"], "jens@goauthentik.io")
Test success with StatusMessage and StatusDetail present (should not raise error)
237 @freeze_time("2022-10-14T14:16:40Z") 238 def test_error_with_message_and_detail(self): 239 """Test error status with StatusMessage and StatusDetail includes both in error""" 240 request = self.factory.post( 241 "/", 242 data={ 243 "SAMLResponse": b64encode( 244 load_fixture("fixtures/response_error_with_detail.xml").encode() 245 ).decode() 246 }, 247 ) 248 249 with self.assertRaises(UnsuccessfulStatus) as ctx: 250 ResponseProcessor(self.source, request).parse() 251 # Should contain both detail and message 252 self.assertIn("User account is disabled", str(ctx.exception)) 253 self.assertIn("Authentication failed", str(ctx.exception))
Test error status with StatusMessage and StatusDetail includes both in error
255 @freeze_time("2024-08-07T15:48:09.325Z") 256 def test_encrypted_correct(self): 257 """Test encrypted""" 258 key = load_fixture("fixtures/encrypted-key.pem") 259 kp = CertificateKeyPair.objects.create( 260 name=generate_id(), 261 key_data=key, 262 ) 263 self.source.encryption_kp = kp 264 request = self.factory.post( 265 "/", 266 data={ 267 "SAMLResponse": b64encode( 268 load_fixture("fixtures/response_encrypted.xml").encode() 269 ).decode() 270 }, 271 ) 272 273 self.source.issuer_override = "authentik-saml-encrypt" 274 parser = ResponseProcessor(self.source, request) 275 with patch( 276 "authentik.sources.saml.processors.response.reverse", return_value=KEYCLOAK_ACS_URL 277 ): 278 parser.parse()
Test encrypted
280 def test_encrypted_incorrect_key(self): 281 """Test encrypted""" 282 kp = create_test_cert() 283 self.source.encryption_kp = kp 284 request = self.factory.post( 285 "/", 286 data={ 287 "SAMLResponse": b64encode( 288 load_fixture("fixtures/response_encrypted.xml").encode() 289 ).decode() 290 }, 291 ) 292 293 parser = ResponseProcessor(self.source, request) 294 with self.assertRaises(InvalidEncryption): 295 parser.parse()
Test encrypted
297 @freeze_time("2022-10-14T14:16:40Z") 298 def test_verification_assertion(self): 299 """Test verifying signature inside assertion""" 300 key = load_fixture("fixtures/signature_cert.pem") 301 kp = CertificateKeyPair.objects.create( 302 name=generate_id(), 303 certificate_data=key, 304 ) 305 self.source.verification_kp = kp 306 self.source.signed_assertion = True 307 self.source.signed_response = False 308 request = self.factory.post( 309 "/", 310 data={ 311 "SAMLResponse": b64encode( 312 load_fixture("fixtures/response_signed_assertion.xml").encode() 313 ).decode() 314 }, 315 ) 316 317 parser = ResponseProcessor(self.source, request) 318 parser.parse()
Test verifying signature inside assertion
320 @freeze_time("2014-07-17T01:02:18Z") 321 def test_verification_assertion_duplicate(self): 322 """Test verifying signature inside assertion, where the response has another assertion 323 before our signed assertion""" 324 key = load_fixture("fixtures/signature_cert.pem") 325 kp = CertificateKeyPair.objects.create( 326 name=generate_id(), 327 certificate_data=key, 328 ) 329 self.source.verification_kp = kp 330 self.source.signed_assertion = True 331 self.source.signed_response = False 332 request = self.factory.post( 333 "/", 334 data={ 335 "SAMLResponse": b64encode( 336 load_fixture("fixtures/response_signed_assertion_dup.xml").encode() 337 ).decode() 338 }, 339 ) 340 341 parser = ResponseProcessor(self.source, request) 342 parser.parse() 343 self.assertNotEqual(parser._get_name_id()[1], "bad") 344 self.assertEqual(parser._get_name_id()[1], "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7")
Test verifying signature inside assertion, where the response has another assertion before our signed assertion
346 @freeze_time("2014-07-17T01:02:18Z") 347 def test_verification_assertion_xsw_nested_duplicate_id(self): 348 """Nested-duplicate-ID XSW: a forged outer Assertion shares its ID with a 349 nested copy of the original signed Assertion (placed inside <saml:Advice>), 350 so the Signature's Reference URI (#ORIG_ID) matches the outer Assertion's 351 ID *and* dereferences to legitimately-signed content. Must be rejected.""" 352 key = load_fixture("fixtures/signature_cert.pem") 353 kp = CertificateKeyPair.objects.create( 354 name=generate_id(), 355 certificate_data=key, 356 ) 357 self.source.verification_kp = kp 358 self.source.signed_assertion = True 359 self.source.signed_response = False 360 request = self.factory.post( 361 "/", 362 data={ 363 "SAMLResponse": b64encode( 364 load_fixture("fixtures/response_signed_assertion_xsw_nested.xml").encode() 365 ).decode() 366 }, 367 ) 368 369 parser = ResponseProcessor(self.source, request) 370 with self.assertRaises(InvalidSignature): 371 parser.parse()
Nested-duplicate-ID XSW: a forged outer Assertion shares its ID with a
nested copy of the original signed Assertion (placed inside
373 @freeze_time("2014-07-17T01:02:18Z") 374 def test_verification_response_uri_empty(self): 375 """Some real-world IdPs (notably some Okta dev-tenant configurations 376 observed in the gosaml2 testdata corpus at saml.oktadev.com) sign the 377 Response with ds:Reference URI="" instead of URI="#<ID>". Per xmldsig 378 §4.4.3.2, URI="" covers the entire enclosing document via the 379 enveloped-signature transform — strictly more attested content than 380 "#<ID>" — so consuming the target is a subset of what was signed.""" 381 key = load_fixture("fixtures/signature_cert_uri_empty.pem") 382 kp = CertificateKeyPair.objects.create( 383 name=generate_id(), 384 certificate_data=key, 385 ) 386 self.source.verification_kp = kp 387 self.source.signed_response = True 388 self.source.signed_assertion = False 389 request = self.factory.post( 390 "/", 391 data={ 392 "SAMLResponse": b64encode( 393 load_fixture("fixtures/response_signed_response_uri_empty.xml").encode() 394 ).decode() 395 }, 396 ) 397 398 parser = ResponseProcessor(self.source, request) 399 parser.parse()
Some real-world IdPs (notably some Okta dev-tenant configurations
observed in the gosaml2 testdata corpus at saml.oktadev.com) sign the
Response with ds:Reference URI="" instead of URI="#
401 @freeze_time("2014-07-17T01:02:18Z") 402 def test_verification_assertion_uri_empty(self): 403 """Symmetric to test_verification_response_uri_empty but for an 404 Assertion-level signature: the same xmldsig "this document" semantics 405 still cover the whole enclosing document, so the Assertion we then 406 consume is part of the attested content. We have no real-world IdP 407 samples emitting this configuration, but the pre-fix code accepted it 408 and the cryptographic guarantee holds, so keep accepting it rather 409 than risk breaking an IdP we haven't sampled.""" 410 key = load_fixture("fixtures/signature_cert_assertion_uri_empty.pem") 411 kp = CertificateKeyPair.objects.create( 412 name=generate_id(), 413 certificate_data=key, 414 ) 415 self.source.verification_kp = kp 416 self.source.signed_assertion = True 417 self.source.signed_response = False 418 request = self.factory.post( 419 "/", 420 data={ 421 "SAMLResponse": b64encode( 422 load_fixture("fixtures/response_signed_assertion_uri_empty.xml").encode() 423 ).decode() 424 }, 425 ) 426 427 parser = ResponseProcessor(self.source, request) 428 parser.parse()
Symmetric to test_verification_response_uri_empty but for an Assertion-level signature: the same xmldsig "this document" semantics still cover the whole enclosing document, so the Assertion we then consume is part of the attested content. We have no real-world IdP samples emitting this configuration, but the pre-fix code accepted it and the cryptographic guarantee holds, so keep accepting it rather than risk breaking an IdP we haven't sampled.
430 @freeze_time("2014-07-17T01:02:18Z") 431 def test_verification_assertion_xsw3(self): 432 """XSW-3 (signature relocation): a forged Assertion contains a Signature whose 433 ds:Reference URI points to a second Assertion in the document. The signature 434 verifies (because the digest matches the legitimate referenced Assertion), 435 but the verifier must NOT then consume the forged Assertion as if it were 436 signed.""" 437 key = load_fixture("fixtures/signature_cert.pem") 438 kp = CertificateKeyPair.objects.create( 439 name=generate_id(), 440 certificate_data=key, 441 ) 442 self.source.verification_kp = kp 443 self.source.signed_assertion = True 444 self.source.signed_response = False 445 request = self.factory.post( 446 "/", 447 data={ 448 "SAMLResponse": b64encode( 449 load_fixture("fixtures/response_signed_assertion_xsw3.xml").encode() 450 ).decode() 451 }, 452 ) 453 454 parser = ResponseProcessor(self.source, request) 455 with self.assertRaises(InvalidSignature): 456 parser.parse()
XSW-3 (signature relocation): a forged Assertion contains a Signature whose ds:Reference URI points to a second Assertion in the document. The signature verifies (because the digest matches the legitimate referenced Assertion), but the verifier must NOT then consume the forged Assertion as if it were signed.
458 @freeze_time("2014-07-17T01:02:18Z") 459 def test_name_id_comment(self): 460 """Test comment in name ID""" 461 fixture = load_fixture("fixtures/response_signed_assertion.xml") 462 fixture = fixture.replace( 463 "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7", 464 "_ce3d2948b4cf20146dee0a0b3dd6f<!--x-->69b6cf86f62d7", 465 ) 466 key = load_fixture("fixtures/signature_cert.pem") 467 kp = CertificateKeyPair.objects.create( 468 name=generate_id(), 469 certificate_data=key, 470 ) 471 self.source.verification_kp = kp 472 self.source.signed_assertion = True 473 self.source.signed_response = False 474 request = self.factory.post( 475 "/", 476 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 477 ) 478 479 parser = ResponseProcessor(self.source, request) 480 parser.parse() 481 self.assertEqual(parser._get_name_id()[1], "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7")
Test comment in name ID
483 @freeze_time("2014-07-17T01:02:18Z") 484 def test_name_id_comment_username_truncation(self): 485 """Test that a comment in the NameID does not truncate the matching username. 486 487 The connection identifier reads the full text content with 488 ``"".join(name_id.itertext())``, so the username used for matching must read 489 the same value and not ``name_id.text``, which returns only the text before 490 the first child node.""" 491 full_name_id = "_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7" 492 # The text before the comment, which is what ``name_id.text`` returns. 493 truncated_name_id = "_ce3d2948b4cf20146dee0a0b3dd6f" 494 commented_name_id = f"{truncated_name_id}<!--x-->{full_name_id[len(truncated_name_id):]}" 495 fixture = load_fixture("fixtures/response_signed_assertion.xml").replace( 496 full_name_id, commented_name_id 497 ) 498 key = load_fixture("fixtures/signature_cert.pem") 499 kp = CertificateKeyPair.objects.create(name=generate_id(), certificate_data=key) 500 self.source.verification_kp = kp 501 self.source.signed_assertion = True 502 self.source.signed_response = False 503 self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK 504 request = self.factory.post( 505 "/", 506 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 507 ) 508 509 parser = ResponseProcessor(self.source, request) 510 # The comment is dropped by the signature canonicalization, so the signature 511 # still verifies. 512 parser.parse() 513 514 name_id_el, identifier = parser._get_name_id() 515 self.assertEqual(identifier, full_name_id) 516 517 properties = self.source.get_base_user_properties( 518 root=parser._root, assertion=parser.get_assertion(), name_id=name_id_el 519 ) 520 # The username must match the full identifier, not the truncated text. 521 self.assertEqual(properties["username"], identifier) 522 523 # An existing user matching only the truncated text must not be linked. 524 other_user = create_test_user(name=truncated_name_id) 525 matcher = SourceMatcher(self.source, UserSAMLSourceConnection, GroupSAMLSourceConnection) 526 action, connection = matcher.get_user_action(identifier, properties) 527 self.assertEqual(action, Action.ENROLL) 528 self.assertNotEqual(connection.user_id, other_user.pk)
Test that a comment in the NameID does not truncate the matching username.
The connection identifier reads the full text content with
"".join(name_id.itertext()), so the username used for matching must read
the same value and not name_id.text, which returns only the text before
the first child node.
530 @freeze_time("2014-07-17T01:02:18Z") 531 def test_attribute_value_comment_truncation(self): 532 """Test that a comment in an attribute value does not truncate it. 533 534 Attribute values feed user matching and property mappings, so a value must 535 be read with ``"".join(value.itertext())`` and not ``value.text``, which 536 returns only the text before the first child node.""" 537 fixture = load_fixture("fixtures/response_signed_assertion.xml").replace( 538 "test@example.com", "test@<!--x-->example.com" 539 ) 540 key = load_fixture("fixtures/signature_cert.pem") 541 kp = CertificateKeyPair.objects.create(name=generate_id(), certificate_data=key) 542 self.source.verification_kp = kp 543 self.source.signed_assertion = True 544 self.source.signed_response = False 545 request = self.factory.post( 546 "/", 547 data={"SAMLResponse": b64encode(fixture.encode()).decode()}, 548 ) 549 550 parser = ResponseProcessor(self.source, request) 551 parser.parse() 552 553 name_id_el, _ = parser._get_name_id() 554 properties = self.source.get_base_user_properties( 555 root=parser._root, assertion=parser.get_assertion(), name_id=name_id_el 556 ) 557 # The attribute value must not be truncated at the comment. 558 self.assertEqual(properties["mail"], "test@example.com")
Test that a comment in an attribute value does not truncate it.
Attribute values feed user matching and property mappings, so a value must
be read with "".join(value.itertext()) and not value.text, which
returns only the text before the first child node.
560 @freeze_time("2014-07-17T01:02:18Z") 561 def test_verification_response(self): 562 """Test verifying signature inside response""" 563 key = load_fixture("fixtures/signature_cert.pem") 564 kp = CertificateKeyPair.objects.create( 565 name=generate_id(), 566 certificate_data=key, 567 ) 568 self.source.verification_kp = kp 569 self.source.signed_response = True 570 self.source.signed_assertion = False 571 request = self.factory.post( 572 "/", 573 data={ 574 "SAMLResponse": b64encode( 575 load_fixture("fixtures/response_signed_response.xml").encode() 576 ).decode() 577 }, 578 ) 579 580 parser = ResponseProcessor(self.source, request) 581 parser.parse()
Test verifying signature inside response
583 @freeze_time("2024-01-18T06:20:48Z") 584 def test_verification_response_and_assertion(self): 585 """Test verifying signature inside response and assertion""" 586 key = load_fixture("fixtures/signature_cert.pem") 587 kp = CertificateKeyPair.objects.create( 588 name=generate_id(), 589 certificate_data=key, 590 ) 591 self.source.verification_kp = kp 592 self.source.signed_assertion = True 593 self.source.signed_response = True 594 request = self.factory.post( 595 "/", 596 data={ 597 "SAMLResponse": b64encode( 598 load_fixture("fixtures/response_signed_response_and_assertion.xml").encode() 599 ).decode() 600 }, 601 ) 602 603 parser = ResponseProcessor(self.source, request) 604 parser.parse()
Test verifying signature inside response and assertion
606 def test_verification_wrong_signature(self): 607 """Test invalid signature fails""" 608 key = load_fixture("fixtures/signature_cert.pem") 609 kp = CertificateKeyPair.objects.create( 610 name=generate_id(), 611 certificate_data=key, 612 ) 613 self.source.verification_kp = kp 614 self.source.signed_assertion = True 615 request = self.factory.post( 616 "/", 617 data={ 618 "SAMLResponse": b64encode( 619 # Same as response_signed_assertion.xml but the role name is altered 620 load_fixture("fixtures/response_signed_error.xml").encode() 621 ).decode() 622 }, 623 ) 624 625 parser = ResponseProcessor(self.source, request) 626 627 with self.assertRaisesMessage(InvalidSignature, ""): 628 parser.parse()
Test invalid signature fails
630 @freeze_time("2022-10-14T14:15:00") 631 def test_verification_no_signature(self): 632 """Test rejecting response without signature when signed_assertion is True""" 633 key = load_fixture("fixtures/signature_cert.pem") 634 kp = CertificateKeyPair.objects.create( 635 name=generate_id(), 636 certificate_data=key, 637 ) 638 self.source.verification_kp = kp 639 self.source.signed_assertion = True 640 request = self.factory.post( 641 "/", 642 data={ 643 "SAMLResponse": b64encode( 644 load_fixture("fixtures/response_success.xml").encode() 645 ).decode() 646 }, 647 ) 648 649 parser = ResponseProcessor(self.source, request) 650 651 with self.assertRaisesMessage(InvalidSignature, ""): 652 parser.parse()
Test rejecting response without signature when signed_assertion is True
654 def test_verification_incorrect_response(self): 655 """Test verifying signature inside response""" 656 key = load_fixture("fixtures/signature_cert.pem") 657 kp = CertificateKeyPair.objects.create( 658 name=generate_id(), 659 certificate_data=key, 660 ) 661 self.source.verification_kp = kp 662 self.source.signed_response = True 663 self.source.signed_assertion = False 664 request = self.factory.post( 665 "/", 666 data={ 667 "SAMLResponse": b64encode( 668 load_fixture("fixtures/response_incorrect_signed_response.xml").encode() 669 ).decode() 670 }, 671 ) 672 673 parser = ResponseProcessor(self.source, request) 674 with self.assertRaisesMessage(InvalidSignature, ""): 675 parser.parse()
Test verifying signature inside response
677 @freeze_time("2025-10-30T05:45:47.619Z") 678 def test_signed_encrypted_response(self): 679 """Test signed & encrypted response""" 680 verification_key = load_fixture("fixtures/signature_cert2.pem") 681 vkp = CertificateKeyPair.objects.create( 682 name=generate_id(), 683 certificate_data=verification_key, 684 ) 685 686 encrypted_key = load_fixture("fixtures/encrypted-key2.pem") 687 ekp = CertificateKeyPair.objects.create(name=generate_id(), key_data=encrypted_key) 688 689 self.source.verification_kp = vkp 690 self.source.encryption_kp = ekp 691 self.source.signed_response = True 692 self.source.signed_assertion = False 693 request = self.factory.post( 694 "/", 695 data={ 696 "SAMLResponse": b64encode( 697 load_fixture("fixtures/response_signed_encrypted.xml").encode() 698 ).decode() 699 }, 700 ) 701 702 self.source.issuer_override = "https://sp.example.org/shibboleth/POST" 703 parser = ResponseProcessor(self.source, request) 704 with patch( 705 "authentik.sources.saml.processors.response.reverse", return_value=SHIBBOLETH_ACS_URL 706 ): 707 parser.parse()
Test signed & encrypted response
709 @freeze_time("2026-01-21T14:23") 710 def test_transient(self): 711 """Test SAML transient NameID""" 712 verification_key = load_fixture("fixtures/signature_cert2.pem") 713 vkp = CertificateKeyPair.objects.create( 714 name=generate_id(), 715 certificate_data=verification_key, 716 ) 717 self.source.verification_kp = vkp 718 self.source.signed_response = True 719 self.source.signed_assertion = False 720 request = self.factory.post( 721 "/", 722 data={ 723 "SAMLResponse": b64encode( 724 load_fixture("fixtures/response_transient.xml").encode() 725 ).decode() 726 }, 727 ) 728 729 self.source.issuer_override = "https://sp.example.org/shibboleth" 730 parser = ResponseProcessor(self.source, request) 731 with patch( 732 "authentik.sources.saml.processors.response.reverse", 733 return_value=SHIBBOLETH_TRANSIENT_ACS_URL, 734 ): 735 parser.parse() 736 parser.prepare_flow_manager()
Test SAML transient NameID
738 def test_doctype(self): 739 """Test that a Response with a document type declaration is refused""" 740 response = load_fixture("fixtures/response_success.xml").replace( 741 '<?xml version="1.0" encoding="UTF-8" standalone="no"?>', 742 '<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE saml2p:Response>', 743 ) 744 request = self.factory.post( 745 "/", 746 data={"SAMLResponse": b64encode(response.encode()).decode()}, 747 ) 748 749 with self.assertRaisesMessage(ValueError, "XML document contains a DOCTYPE declaration"): 750 ResponseProcessor(self.source, request).parse()
Test that a Response with a document type declaration is refused