def test_verify_xml_signatures_success(self): with cast(TextIO, (DATA_DIR / 'signed_response.xml').open('r')) as f: tree = parse_xml(f.read()) remove_extra_xml_whitespace( tree) # Reverts pretty printing applied after signing verify_xml_signatures(tree, CERT_FILE)
def test_verify_xml_signatures_ref_not_found(self): root = Element('root') signature = SubElement(root, QName(XML_SIG_NAMESPACE, 'Signature')) info = SubElement(signature, QName(XML_SIG_NAMESPACE, 'SignedInfo')) SubElement(info, QName(XML_SIG_NAMESPACE, 'Reference'), {'URI': '#id'}) with self.assertRaisesMessage( SecurityError, "Signature 1, reference 1: Element with id 'id' not found."): verify_xml_signatures(root, CERT_FILE)
def verify_request(self, cert_file: str) -> None: """Verify XML signature of the whole request.""" signature = self.request_signature if signature is None: raise SecurityError('Signature does not exist.') # We need to check not only that a valid signature exists but it must also reference the correct element. for valid_signature, references in verify_xml_signatures(self.document.getroot(), cert_file): if valid_signature is signature: if signature.getparent() not in references: raise SecurityError('Signature does not reference parent element.') break else: raise SecurityError('Signature not found.')
def _verify_and_remove_signature(self, signature: Optional[Element], cert_file: str) -> None: """Verify signature and remove it from document.""" if signature is None: raise SecurityError('Signature does not exist.') # We need to check not only that a valid signature exists but it must also reference the correct element. for valid_signature, references in verify_xml_signatures(self.document.getroot(), cert_file): if valid_signature is signature: if signature.getparent() not in references: raise SecurityError('Signature does not reference parent element.') # Remove the signature as further document manipulations might invalidate it. # E.g., decrypting an encrypted assertion invalidates signature of the whole response. signature.getparent().remove(signature) break else: raise SecurityError('Signature not found.')
def test_verify_xml_signatures_nia(self): with cast(TextIO, (DATA_DIR / 'nia_test_response.xml').open('r')) as f: tree = parse_xml(f.read()) remove_extra_xml_whitespace(tree) verify_xml_signatures(tree, NIA_CERT_FILE)
def test_verify_xml_signatures_no_signatures(self): root = Element('root') self.assertEqual(verify_xml_signatures(root, CERT_FILE), [])