Changed and/or added tests

This commit is contained in:
Roland Hedberg
2010-07-21 13:14:26 +02:00
parent 73b55e082f
commit fd5dc7c2dd
8 changed files with 4576 additions and 0 deletions

659
tests/test_00_xmldsig.py Normal file
View File

@@ -0,0 +1,659 @@
#!/usr/bin/python
#
# Copyright (C) 2007 SIOS Technology, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for xmldsig"""
__author__ = 'tmatsuo@example.com (Takashi MATSUO)'
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import ds_data
import xmldsig as ds
class TestObject:
def setup_class(self):
self.object = ds.Object()
def testAccessors(self):
"""Test for Object accessors"""
self.object.id = "object_id"
self.object.mime_type = "test/plain; charset=UTF-8"
self.object.encoding = ds.ENCODING_BASE64
new_object = ds.object_from_string(self.object.to_string())
assert new_object.id == "object_id"
assert new_object.mime_type == "test/plain; charset=UTF-8"
assert new_object.encoding == ds.ENCODING_BASE64
def testUsingTestData(self):
"""Test for object_from_string() using test data"""
new_object = ds.object_from_string(ds_data.TEST_OBJECT)
assert new_object.id == "object_id"
assert new_object.encoding == ds.ENCODING_BASE64
assert new_object.text.strip() == \
"V2VkIEp1biAgNCAxMjoxMTowMyBFRFQgMjAwMwo"
class TestMgmtData:
def setup_class(self):
self.mgmt_data = ds.MgmtData()
def testAccessors(self):
"""Test for MgmtData accessors"""
self.mgmt_data.text = "mgmt data"
new_mgmt_data = ds.mgmt_data_from_string(self.mgmt_data.to_string())
assert new_mgmt_data.text.strip() == "mgmt data"
def testUsingTestData(self):
"""Test for mgmt_data_from_string() using test data"""
new_mgmt_data = ds.mgmt_data_from_string(ds_data.TEST_MGMT_DATA)
assert new_mgmt_data.text.strip() == "mgmt data"
class TestSPKISexp:
def setup_class(self):
self.spki_sexp = ds.SPKISexp()
def testAccessors(self):
"""Test for SPKISexp accessors"""
self.spki_sexp.text = "spki sexp"
new_spki_sexp = ds.spki_sexp_from_string(self.spki_sexp.to_string())
assert new_spki_sexp.text.strip() == "spki sexp"
def testUsingTestData(self):
"""Test for spki_sexp_from_string() using test data"""
new_spki_sexp = ds.spki_sexp_from_string(ds_data.TEST_SPKI_SEXP)
assert new_spki_sexp.text.strip() == "spki sexp"
class TestSPKIData:
def setup_class(self):
self.spki_data = ds.SPKIData()
def testAccessors(self):
"""Test for SPKIData accessors"""
self.spki_data.spki_sexp.append(
ds.spki_sexp_from_string(ds_data.TEST_SPKI_SEXP))
new_spki_data = ds.spki_data_from_string(self.spki_data.to_string())
assert new_spki_data.spki_sexp[0].text.strip() == "spki sexp"
def testUsingTestData(self):
"""Test for spki_data_from_string() using test data"""
new_spki_data = ds.spki_data_from_string(ds_data.TEST_SPKI_DATA)
assert new_spki_data.spki_sexp[0].text.strip() == "spki sexp"
assert new_spki_data.spki_sexp[1].text.strip() == "spki sexp2"
class TestPGPData:
def setup_class(self):
self.pgp_data = ds.PGPData()
def testAccessors(self):
"""Test for PGPData accessors"""
self.pgp_data.pgp_key_id = ds.PGPKeyID(text="pgp key id")
self.pgp_data.pgp_key_packet = ds.PGPKeyPacket(text="pgp key packet")
new_pgp_data = ds.pgp_data_from_string(self.pgp_data.to_string())
assert isinstance(new_pgp_data.pgp_key_id, ds.PGPKeyID)
assert isinstance(new_pgp_data.pgp_key_packet, ds.PGPKeyPacket)
assert new_pgp_data.pgp_key_id.text.strip() == "pgp key id"
assert new_pgp_data.pgp_key_packet.text.strip() == "pgp key packet"
def testUsingTestData(self):
"""Test for pgp_data_from_string() using test data"""
new_pgp_data = ds.pgp_data_from_string(ds_data.TEST_PGP_DATA)
assert isinstance(new_pgp_data.pgp_key_id, ds.PGPKeyID)
assert isinstance(new_pgp_data.pgp_key_packet, ds.PGPKeyPacket)
assert new_pgp_data.pgp_key_id.text.strip() == "pgp key id"
assert new_pgp_data.pgp_key_packet.text.strip() == "pgp key packet"
class TestX509IssuerSerial:
def setup_class(self):
self.x509_issuer_serial = ds.X509IssuerSerialType()
def testAccessors(self):
"""Test for X509SerialNumber accessors"""
self.x509_issuer_serial.x509_issuer_name = ds.X509IssuerName(
text="issuer name")
self.x509_issuer_serial.x509_serial_number = ds.X509SerialNumber(text="1")
new_x509_issuer_serial = ds.x509_issuer_serial_type_from_string(
self.x509_issuer_serial.to_string())
assert new_x509_issuer_serial.x509_issuer_name.text.strip() == \
"issuer name"
assert new_x509_issuer_serial.x509_serial_number.text.strip() == "1"
def testUsingTestData(self):
"""Test for x509_issuer_serial_from_string() using test data"""
new_x509_issuer_serial = ds.x509_issuer_serial_from_string(
ds_data.TEST_X509_ISSUER_SERIAL)
assert new_x509_issuer_serial.x509_issuer_name.text.strip() == \
"issuer name"
assert new_x509_issuer_serial.x509_serial_number.text.strip() == "1"
class TestX509Data:
def setup_class(self):
self.x509_data = ds.X509Data()
def testAccessors(self):
"""Test for X509Data accessors"""
st = ds.x509_issuer_serial_from_string(ds_data.TEST_X509_ISSUER_SERIAL)
print st
self.x509_data.x509_issuer_serial.append(st)
self.x509_data.x509_ski.append(ds.X509SKI(text="x509 ski"))
self.x509_data.x509_subject_name.append(ds.X509SubjectName(
text="x509 subject name"))
self.x509_data.x509_certificate.append(ds.X509Certificate(
text="x509 certificate"))
self.x509_data.x509_crl.append(ds.X509CRL(text="x509 crl"))
new_x509_data = ds.x509_data_from_string(self.x509_data.to_string())
print new_x509_data.keyswv()
print new_x509_data.__dict__.keys()
print len(new_x509_data.x509_issuer_serial)
assert isinstance(new_x509_data.x509_issuer_serial[0],
ds.X509IssuerSerialType)
assert new_x509_data.x509_ski[0].text.strip() == "x509 ski"
assert isinstance(new_x509_data.x509_ski[0], ds.X509SKI)
assert new_x509_data.x509_subject_name[0].text.strip() == \
"x509 subject name"
assert isinstance(new_x509_data.x509_subject_name[0],
ds.X509SubjectName)
assert new_x509_data.x509_certificate[0].text.strip() == \
"x509 certificate"
assert isinstance(new_x509_data.x509_certificate[0],
ds.X509Certificate)
assert new_x509_data.x509_crl[0].text.strip() == "x509 crl"
assert isinstance(new_x509_data.x509_crl[0],ds.X509CRL)
def testUsingTestData(self):
"""Test for x509_data_from_string() using test data"""
new_x509_data = ds.x509_data_from_string(ds_data.TEST_X509_DATA)
assert isinstance(new_x509_data.x509_issuer_serial[0],
ds.X509IssuerSerial)
assert new_x509_data.x509_ski[0].text.strip() == "x509 ski"
assert isinstance(new_x509_data.x509_ski[0], ds.X509SKI)
assert new_x509_data.x509_subject_name[0].text.strip() == \
"x509 subject name"
assert isinstance(new_x509_data.x509_subject_name[0],
ds.X509SubjectName)
assert new_x509_data.x509_certificate[0].text.strip() == \
"x509 certificate"
assert isinstance(new_x509_data.x509_certificate[0],
ds.X509Certificate)
assert new_x509_data.x509_crl[0].text.strip() == "x509 crl"
assert isinstance(new_x509_data.x509_crl[0],ds.X509CRL)
class TestTransform:
def setup_class(self):
self.transform = ds.Transform()
def testAccessors(self):
"""Test for Transform accessors"""
self.transform.x_path.append(ds.XPath(text="xpath"))
self.transform.algorithm = ds.TRANSFORM_ENVELOPED
new_transform = ds.transform_from_string(self.transform.to_string())
assert isinstance(new_transform.x_path[0], ds.XPath)
assert new_transform.x_path[0].text.strip() == "xpath"
assert new_transform.algorithm == ds.TRANSFORM_ENVELOPED
def testUsingTestData(self):
"""Test for transform_from_string() using test data"""
new_transform = ds.transform_from_string(ds_data.TEST_TRANSFORM)
assert isinstance(new_transform.x_path[0], ds.XPath)
assert new_transform.x_path[0].text.strip() == "xpath"
assert new_transform.algorithm == ds.TRANSFORM_ENVELOPED
class TestTransforms:
def setup_class(self):
self.transforms = ds.Transforms()
def testAccessors(self):
"""Test for Transforms accessors"""
self.transforms.transform.append(
ds.transform_from_string(ds_data.TEST_TRANSFORM))
self.transforms.transform.append(
ds.transform_from_string(ds_data.TEST_TRANSFORM))
new_transforms = ds.transforms_from_string(self.transforms.to_string())
assert isinstance(new_transforms.transform[0], ds.Transform)
assert isinstance(new_transforms.transform[1], ds.Transform)
assert new_transforms.transform[0].algorithm == \
ds.TRANSFORM_ENVELOPED
assert new_transforms.transform[1].algorithm == \
ds.TRANSFORM_ENVELOPED
assert new_transforms.transform[0].x_path[0].text.strip() == "xpath"
assert new_transforms.transform[1].x_path[0].text.strip() == "xpath"
def testUsingTestData(self):
"""Test for transform_from_string() using test data"""
new_transforms = ds.transforms_from_string(ds_data.TEST_TRANSFORMS)
assert isinstance(new_transforms.transform[0], ds.Transform)
assert isinstance(new_transforms.transform[1], ds.Transform)
assert new_transforms.transform[0].algorithm == \
ds.TRANSFORM_ENVELOPED
assert new_transforms.transform[1].algorithm == \
ds.TRANSFORM_ENVELOPED
assert new_transforms.transform[0].x_path[0].text.strip() == "xpath"
assert new_transforms.transform[1].x_path[0].text.strip() == "xpath"
class TestRetrievalMethod:
def setup_class(self):
self.retrieval_method = ds.RetrievalMethod()
def testAccessors(self):
"""Test for RetrievalMethod accessors"""
self.retrieval_method.uri = "http://www.example.com/URI"
self.retrieval_method.type = "http://www.example.com/Type"
self.retrieval_method.transforms = ds.transforms_from_string(
ds_data.TEST_TRANSFORMS)
new_retrieval_method = ds.retrieval_method_from_string(
self.retrieval_method.to_string())
assert new_retrieval_method.uri == "http://www.example.com/URI"
assert new_retrieval_method.type == "http://www.example.com/Type"
assert isinstance(new_retrieval_method.transforms, ds.Transforms)
def testUsingTestData(self):
"""Test for retrieval_method_from_string() using test data"""
new_retrieval_method = ds.retrieval_method_from_string(
ds_data.TEST_RETRIEVAL_METHOD)
assert new_retrieval_method.uri == "http://www.example.com/URI"
assert new_retrieval_method.type == "http://www.example.com/Type"
assert isinstance(new_retrieval_method.transforms, ds.Transforms)
class TestRSAKeyValue:
def setup_class(self):
self.rsa_key_value = ds.RSAKeyValue()
def testAccessors(self):
"""Test for RSAKeyValue accessors"""
self.rsa_key_value.modulus = ds.Modulus(text="modulus")
self.rsa_key_value.exponent = ds.Exponent(text="exponent")
new_rsa_key_value = ds.rsa_key_value_from_string(self.rsa_key_value.to_string())
assert isinstance(new_rsa_key_value.modulus, ds.Modulus)
assert isinstance(new_rsa_key_value.exponent, ds.Exponent)
assert new_rsa_key_value.modulus.text.strip() == "modulus"
assert new_rsa_key_value.exponent.text.strip() == "exponent"
def testUsingTestData(self):
"""Test for rsa_key_value_from_string() using test data"""
new_rsa_key_value = ds.rsa_key_value_from_string(
ds_data.TEST_RSA_KEY_VALUE)
assert isinstance(new_rsa_key_value.modulus, ds.Modulus)
assert isinstance(new_rsa_key_value.exponent, ds.Exponent)
assert new_rsa_key_value.modulus.text.strip() == "modulus"
assert new_rsa_key_value.exponent.text.strip() == "exponent"
class TestDSAKeyValue:
def setup_class(self):
self.dsa_key_value = ds.DSAKeyValue()
def testAccessors(self):
"""Test for DSAKeyValue accessors"""
self.dsa_key_value.p = ds.P(text="p")
self.dsa_key_value.q = ds.Q(text="q")
self.dsa_key_value.g = ds.G(text="g")
self.dsa_key_value.y = ds.Y(text="y")
self.dsa_key_value.j = ds.J(text="j")
self.dsa_key_value.seed = ds.Seed(text="seed")
self.dsa_key_value.pgen_counter = ds.PgenCounter(text="pgen counter")
new_dsa_key_value = ds.dsa_key_value_from_string(self.dsa_key_value.to_string())
assert isinstance(new_dsa_key_value.p, ds.P)
assert isinstance(new_dsa_key_value.q, ds.Q)
assert isinstance(new_dsa_key_value.g, ds.G)
assert isinstance(new_dsa_key_value.y, ds.Y)
assert isinstance(new_dsa_key_value.j, ds.J)
assert isinstance(new_dsa_key_value.seed, ds.Seed)
assert isinstance(new_dsa_key_value.pgen_counter, ds.PgenCounter)
assert new_dsa_key_value.p.text.strip() == "p"
assert new_dsa_key_value.q.text.strip() == "q"
assert new_dsa_key_value.g.text.strip() == "g"
assert new_dsa_key_value.y.text.strip() == "y"
assert new_dsa_key_value.j.text.strip() == "j"
assert new_dsa_key_value.seed.text.strip() == "seed"
assert new_dsa_key_value.pgen_counter.text.strip() == "pgen counter"
def testUsingTestData(self):
"""Test for dsa_key_value_from_string() using test data"""
new_dsa_key_value = ds.dsa_key_value_from_string(
ds_data.TEST_DSA_KEY_VALUE)
assert isinstance(new_dsa_key_value.p, ds.P)
assert isinstance(new_dsa_key_value.q, ds.Q)
assert isinstance(new_dsa_key_value.g, ds.G)
assert isinstance(new_dsa_key_value.y, ds.Y)
assert isinstance(new_dsa_key_value.j, ds.J)
assert isinstance(new_dsa_key_value.seed, ds.Seed)
assert isinstance(new_dsa_key_value.pgen_counter, ds.PgenCounter)
assert new_dsa_key_value.p.text.strip() == "p"
assert new_dsa_key_value.q.text.strip() == "q"
assert new_dsa_key_value.g.text.strip() == "g"
assert new_dsa_key_value.y.text.strip() == "y"
assert new_dsa_key_value.j.text.strip() == "j"
assert new_dsa_key_value.seed.text.strip() == "seed"
assert new_dsa_key_value.pgen_counter.text.strip() == "pgen counter"
class TestKeyValue:
def setup_class(self):
self.key_value = ds.KeyValue()
def testAccessors(self):
"""Test for KeyValue accessors"""
self.key_value.dsa_key_value = ds.dsa_key_value_from_string(
ds_data.TEST_DSA_KEY_VALUE)
new_key_value = ds.key_value_from_string(self.key_value.to_string())
assert isinstance(new_key_value.dsa_key_value, ds.DSAKeyValue)
self.key_value.dsa_key_value = None
self.key_value.rsa_key_value = ds.rsa_key_value_from_string(
ds_data.TEST_RSA_KEY_VALUE)
new_key_value = ds.key_value_from_string(self.key_value.to_string())
assert isinstance(new_key_value.rsa_key_value, ds.RSAKeyValue)
def testUsingTestData(self):
"""Test for key_value_from_string() using test data"""
new_key_value = ds.key_value_from_string(ds_data.TEST_KEY_VALUE1)
assert isinstance(new_key_value.dsa_key_value, ds.DSAKeyValue)
self.key_value.dsa_key_value = None
self.key_value.rsa_key_value = ds.rsa_key_value_from_string(
ds_data.TEST_RSA_KEY_VALUE)
new_key_value = ds.key_value_from_string(ds_data.TEST_KEY_VALUE2)
assert isinstance(new_key_value.rsa_key_value, ds.RSAKeyValue)
class TestKeyName:
def setup_class(self):
self.key_name = ds.KeyName()
def testAccessors(self):
"""Test for KeyName accessors"""
self.key_name.text = "key name"
new_key_name = ds.key_name_from_string(self.key_name.to_string())
assert new_key_name.text.strip() == "key name"
def testUsingTestData(self):
"""Test for key_name_from_string() using test data"""
new_key_name = ds.key_name_from_string(ds_data.TEST_KEY_NAME)
assert new_key_name.text.strip() == "key name"
class TestKeyInfo:
def setup_class(self):
self.key_info = ds.KeyInfo()
def testAccessors(self):
"""Test for KeyInfo accessors"""
self.key_info.key_name.append(
ds.key_name_from_string(ds_data.TEST_KEY_NAME))
self.key_info.key_value.append(
ds.key_value_from_string(ds_data.TEST_KEY_VALUE1))
self.key_info.retrieval_method.append(
ds.retrieval_method_from_string(ds_data.TEST_RETRIEVAL_METHOD))
self.key_info.x509_data.append(
ds.x509_data_from_string(ds_data.TEST_X509_DATA))
self.key_info.pgp_data.append(
ds.pgp_data_from_string(ds_data.TEST_PGP_DATA))
self.key_info.spki_data.append(
ds.spki_data_from_string(ds_data.TEST_SPKI_DATA))
self.key_info.mgmt_data.append(
ds.mgmt_data_from_string(ds_data.TEST_MGMT_DATA))
self.key_info.id = "id"
new_key_info = ds.key_info_from_string(self.key_info.to_string())
assert isinstance(new_key_info.key_name[0], ds.KeyName)
assert isinstance(new_key_info.key_value[0], ds.KeyValue)
assert isinstance(new_key_info.retrieval_method[0],
ds.RetrievalMethod)
assert isinstance(new_key_info.x509_data[0], ds.X509Data)
assert isinstance(new_key_info.pgp_data[0], ds.PGPData)
assert isinstance(new_key_info.spki_data[0], ds.SPKIData)
assert isinstance(new_key_info.mgmt_data[0], ds.MgmtData)
assert new_key_info.id == "id"
def testUsingTestData(self):
"""Test for key_info_from_string() using test data"""
new_key_info = ds.key_info_from_string(ds_data.TEST_KEY_INFO)
assert isinstance(new_key_info.key_name[0], ds.KeyName)
assert isinstance(new_key_info.key_value[0], ds.KeyValue)
assert isinstance(new_key_info.retrieval_method[0],
ds.RetrievalMethod)
assert isinstance(new_key_info.x509_data[0], ds.X509Data)
assert isinstance(new_key_info.pgp_data[0], ds.PGPData)
assert isinstance(new_key_info.spki_data[0], ds.SPKIData)
assert isinstance(new_key_info.mgmt_data[0], ds.MgmtData)
assert new_key_info.id == "id"
class TestDigestValue:
def setup_class(self):
self.digest_value = ds.DigestValue()
def testAccessors(self):
"""Test for DigestValue accessors"""
self.digest_value.text = "digest value"
new_digest_value = ds.digest_value_from_string(self.digest_value.to_string())
assert new_digest_value.text.strip() == "digest value"
def testUsingTestData(self):
"""Test for digest_value_from_string() using test data"""
new_digest_value = ds.digest_value_from_string(ds_data.TEST_DIGEST_VALUE)
assert new_digest_value.text.strip() == "digest value"
class TestDigestMethod:
def setup_class(self):
self.digest_method = ds.DigestMethod()
def testAccessors(self):
"""Test for DigestMethod accessors"""
self.digest_method.algorithm = ds.DIGEST_SHA1
new_digest_method = ds.digest_method_from_string(
self.digest_method.to_string())
assert new_digest_method.algorithm == ds.DIGEST_SHA1
def testUsingTestData(self):
"""Test for digest_method_from_string() using test data"""
new_digest_method = ds.digest_method_from_string(
ds_data.TEST_DIGEST_METHOD)
assert new_digest_method.algorithm == ds.DIGEST_SHA1
class TestReference:
def setup_class(self):
self.reference = ds.Reference()
def testAccessors(self):
"""Test for Reference accessors"""
self.reference.transforms = ds.transforms_from_string(
ds_data.TEST_TRANSFORMS)
self.reference.digest_method = ds.digest_method_from_string(
ds_data.TEST_DIGEST_METHOD)
self.reference.digest_value = ds.digest_value_from_string(
ds_data.TEST_DIGEST_VALUE)
self.reference.id = "id"
self.reference.uri = "http://www.example.com/URI"
self.reference.type = "http://www.example.com/Type"
new_reference = ds.reference_from_string(self.reference.to_string())
assert isinstance(new_reference.transforms, ds.Transforms)
assert isinstance(new_reference.digest_method, ds.DigestMethod)
assert isinstance(new_reference.digest_value, ds.DigestValue)
assert new_reference.id == "id"
assert new_reference.uri == "http://www.example.com/URI"
assert new_reference.type == "http://www.example.com/Type"
def testUsingTestData(self):
"""Test for reference_from_string() using test data"""
new_reference = ds.reference_from_string(ds_data.TEST_REFERENCE)
assert isinstance(new_reference.transforms, ds.Transforms)
assert isinstance(new_reference.digest_method, ds.DigestMethod)
assert isinstance(new_reference.digest_value, ds.DigestValue)
assert new_reference.id == "id"
assert new_reference.uri == "http://www.example.com/URI"
assert new_reference.type == "http://www.example.com/Type"
class TestSignatureMethod:
def setup_class(self):
self.signature_method = ds.SignatureMethod()
def testAccessors(self):
"""Test for SignatureMethod accessors"""
self.signature_method.algorithm = ds.SIG_RSA_SHA1
self.signature_method.hmac_output_length = ds.HMACOutputLength(text="8")
new_signature_method = ds.signature_method_from_string(
self.signature_method.to_string())
assert isinstance(new_signature_method.hmac_output_length,
ds.HMACOutputLength)
assert new_signature_method.hmac_output_length.text.strip() == "8"
assert new_signature_method.algorithm == ds.SIG_RSA_SHA1
def testUsingTestData(self):
"""Test for signature_method_from_string() using test data"""
new_signature_method = ds.signature_method_from_string(
ds_data.TEST_SIGNATURE_METHOD)
assert isinstance(new_signature_method.hmac_output_length,
ds.HMACOutputLength)
assert new_signature_method.hmac_output_length.text.strip() == "8"
assert new_signature_method.algorithm == ds.SIG_RSA_SHA1
class TestCanonicalizationMethod:
def setup_class(self):
self.canonicalization_method = ds.CanonicalizationMethod()
def testAccessors(self):
"""Test for CanonicalizationMethod accessors"""
self.canonicalization_method.algorithm = ds.C14N_WITH_C
new_canonicalization_method = ds.canonicalization_method_from_string(
self.canonicalization_method.to_string())
assert new_canonicalization_method.algorithm == ds.C14N_WITH_C
def testUsingTestData(self):
"""Test for canonicalization_method_from_string() using test data"""
new_canonicalization_method = ds.canonicalization_method_from_string(
ds_data.TEST_CANONICALIZATION_METHOD)
assert new_canonicalization_method.algorithm == ds.C14N_WITH_C
class TestSignedInfo:
def setup_class(self):
self.si = ds.SignedInfo()
def testAccessors(self):
"""Test for SignedInfo accessors"""
self.si.id = "id"
self.si.canonicalization_method = ds.canonicalization_method_from_string(
ds_data.TEST_CANONICALIZATION_METHOD)
self.si.signature_method = ds.signature_method_from_string(
ds_data.TEST_SIGNATURE_METHOD)
self.si.reference.append(ds.reference_from_string(
ds_data.TEST_REFERENCE))
new_si = ds.signed_info_from_string(self.si.to_string())
assert new_si.id == "id"
assert isinstance(new_si.canonicalization_method,
ds.CanonicalizationMethod)
assert isinstance(new_si.signature_method, ds.SignatureMethod)
assert isinstance(new_si.reference[0], ds.Reference)
def testUsingTestData(self):
"""Test for signed_info_from_string() using test data"""
new_si = ds.signed_info_from_string(ds_data.TEST_SIGNED_INFO)
assert new_si.id == "id"
assert isinstance(new_si.canonicalization_method,
ds.CanonicalizationMethod)
assert isinstance(new_si.signature_method, ds.SignatureMethod)
assert isinstance(new_si.reference[0], ds.Reference)
class TestSignatureValue:
def setup_class(self):
self.signature_value = ds.SignatureValue()
def testAccessors(self):
"""Test for SignatureValue accessors"""
self.signature_value.id = "id"
self.signature_value.text = "signature value"
new_signature_value = ds.signature_value_from_string(
self.signature_value.to_string())
assert new_signature_value.id == "id"
assert new_signature_value.text.strip() == "signature value"
def testUsingTestData(self):
"""Test for signature_value_from_string() using test data"""
new_signature_value = ds.signature_value_from_string(
ds_data.TEST_SIGNATURE_VALUE)
assert new_signature_value.id == "id"
assert new_signature_value.text.strip() == "signature value"
class TestSignature:
def setup_class(self):
self.signature = ds.Signature()
def testAccessors(self):
"""Test for Signature accessors"""
self.signature.id = "id"
self.signature.signed_info = ds.signed_info_from_string(
ds_data.TEST_SIGNED_INFO)
self.signature.signature_value = ds.signature_value_from_string(
ds_data.TEST_SIGNATURE_VALUE)
self.signature.key_info = ds.key_info_from_string(ds_data.TEST_KEY_INFO)
self.signature.object.append(ds.object_from_string(ds_data.TEST_OBJECT))
new_signature = ds.signature_from_string(self.signature.to_string())
assert new_signature.id == "id"
assert isinstance(new_signature.signed_info, ds.SignedInfo)
assert isinstance(new_signature.signature_value, ds.SignatureValue)
assert isinstance(new_signature.key_info, ds.KeyInfo)
assert isinstance(new_signature.object[0], ds.Object)
def testUsingTestData(self):
"""Test for signature_value_from_string() using test data"""
new_signature = ds.signature_from_string(ds_data.TEST_SIGNATURE)
assert new_signature.id == "id"
assert isinstance(new_signature.signed_info, ds.SignedInfo)
assert isinstance(new_signature.signature_value, ds.SignatureValue)
assert isinstance(new_signature.key_info, ds.KeyInfo)
assert isinstance(new_signature.object[0], ds.Object)
if __name__ == '__main__':
unittest.main()

209
tests/test_01_xmlenc.py Normal file
View File

@@ -0,0 +1,209 @@
import saml2
import xmlenc as xenc
import xmldsig
data1 = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:EncryptedData MimeType="text/xml" xmlns:ns0="http://www.w3.org/2001/04/xmlenc#">
<ns0:CipherData>
<ns0:CipherValue>A23B45C56</ns0:CipherValue>
</ns0:CipherData>
</ns0:EncryptedData>"""
def test_1():
ed = xenc.encrypted_data_from_string(data1)
assert ed
assert ed.mime_type == "text/xml"
assert ed.cipher_data != None
cd = ed.cipher_data
assert cd.cipher_value != None
assert cd.cipher_value.text == "A23B45C56"
data2 = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:EncryptedData
Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns:ns0="http://www.w3.org/2001/04/xmlenc#">
<ns0:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<ns1:KeyInfo xmlns:ns1="http://www.w3.org/2000/09/xmldsig#">
<ns1:KeyName>John Smith</ns1:KeyName>
</ns1:KeyInfo>
<ns0:CipherData>
<ns0:CipherValue>DEADBEEF</ns0:CipherValue>
</ns0:CipherData>
</ns0:EncryptedData>"""
# data2 = """<EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#'
# Type='http://www.w3.org/2001/04/xmlenc#Element'>
# <EncryptionMethod
# Algorithm='http://www.w3.org/2001/04/xmlenc#tripledes-cbc'/>
# <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
# <ds:KeyName>John Smith</ds:KeyName>
# </ds:KeyInfo>
# <CipherData><CipherValue>DEADBEEF</CipherValue></CipherData>
# </EncryptedData>"""
def test_2():
ed = xenc.encrypted_data_from_string(data2)
assert ed
print ed
assert ed.type == "http://www.w3.org/2001/04/xmlenc#Element"
assert ed.encryption_method != None
em = ed.encryption_method
assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc'
assert ed.key_info != None
ki = ed.key_info
assert ki.key_name[0].text == "John Smith"
assert ed.cipher_data != None
cd = ed.cipher_data
assert cd.cipher_value != None
assert cd.cipher_value.text == "DEADBEEF"
data3 = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:EncryptedData
Id="ED"
xmlns:ns0="http://www.w3.org/2001/04/xmlenc#">
<ns0:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc" />
<ns1:KeyInfo xmlns:ns1="http://www.w3.org/2000/09/xmldsig#">
<ns1:RetrievalMethod URI='#EK'
Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
<ns1:KeyName>Sally Doe</ns1:KeyName>
</ns1:KeyInfo>
<ns0:CipherData>
<ns0:CipherValue>DEADBEEF</ns0:CipherValue>
</ns0:CipherData>
</ns0:EncryptedData>"""
def test_3():
ed = xenc.encrypted_data_from_string(data3)
assert ed
print ed
assert ed.encryption_method != None
em = ed.encryption_method
assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#aes128-cbc'
assert ed.key_info != None
ki = ed.key_info
assert ki.key_name[0].text == "Sally Doe"
assert len(ki.retrieval_method) == 1
rm = ki.retrieval_method[0]
assert rm.uri == "#EK"
assert rm.type == "http://www.w3.org/2001/04/xmlenc#EncryptedKey"
assert ed.cipher_data != None
cd = ed.cipher_data
assert cd.cipher_value != None
assert cd.cipher_value.text == "DEADBEEF"
data4 = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:EncryptedKey
Id="EK"
xmlns:ns0="http://www.w3.org/2001/04/xmlenc#">
<ns0:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<ns1:KeyInfo xmlns:ns1="http://www.w3.org/2000/09/xmldsig#">
<ns1:KeyName>John Smith</ns1:KeyName>
</ns1:KeyInfo>
<ns0:CipherData>
<ns0:CipherValue>xyzabc</ns0:CipherValue>
</ns0:CipherData>
<ns0:ReferenceList>
<ns0:DataReference URI='#ED'/>
</ns0:ReferenceList>
<ns0:CarriedKeyName>Sally Doe</ns0:CarriedKeyName>
</ns0:EncryptedKey>"""
# data4 = """<EncryptedKey Id='EK' xmlns='http://www.w3.org/2001/04/xmlenc#'>
# <EncryptionMethod
# Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
# <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
# <ds:KeyName>John Smith</ds:KeyName>
# </ds:KeyInfo>
# <CipherData><CipherValue>xyzabc</CipherValue></CipherData>
# <ReferenceList>
# <DataReference URI='#ED'/>
# </ReferenceList>
# <CarriedKeyName>Sally Doe</CarriedKeyName>
# </EncryptedKey>"""
def test_4():
ek = xenc.encrypted_key_from_string(data4)
assert ek
print ek
assert ek.encryption_method != None
em = ek.encryption_method
assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#rsa-1_5'
assert ek.key_info != None
ki = ek.key_info
assert ki.key_name[0].text == "John Smith"
assert ek.reference_list != None
rl = ek.reference_list
assert len(rl.data_reference)
dr = rl.data_reference[0]
assert dr.uri == "#ED"
assert ek.cipher_data != None
cd = ek.cipher_data
assert cd.cipher_value != None
assert cd.cipher_value.text == "xyzabc"
data5 = """<CipherReference URI="http://www.example.com/CipherValues.xml"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<Transforms xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
<ds:Transform
Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
<ds:XPath xmlns:rep="http://www.example.org/repository">
self::text()[parent::rep:CipherValue[@Id="example1"]]
</ds:XPath>
</ds:Transform>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#base64"/>
</Transforms>
</CipherReference>"""
def test_5():
cr = xenc.cipher_reference_from_string(data5)
assert cr
print cr
print cr.keyswv()
trs = cr.transforms
assert len(trs.transform) == 2
tr = trs.transform[0]
assert tr.algorithm in ["http://www.w3.org/TR/1999/REC-xpath-19991116",
"http://www.w3.org/2000/09/xmldsig#base64"]
if tr.algorithm == "http://www.w3.org/2000/09/xmldsig#base64":
pass
elif tr.algorithm == "http://www.w3.org/TR/1999/REC-xpath-19991116":
assert len(tr.x_path) == 1
xp = tr.x_path[0]
assert xp.text.strip() == """self::text()[parent::rep:CipherValue[@Id="example1"]]"""
data6 = """<ReferenceList xmlns="http://www.w3.org/2001/04/xmlenc#">
<DataReference URI="#invoice34">
<ds:Transforms xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
<ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
<ds:XPath xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
self::xenc:EncryptedData[@Id="example1"]
</ds:XPath>
</ds:Transform>
</ds:Transforms>
</DataReference>
</ReferenceList>"""
def test_6():
rl = xenc.reference_list_from_string(data6)
assert rl
print rl
assert len(rl.data_reference) == 1
dr = rl.data_reference[0]
assert dr.uri == "#invoice34"
assert len(dr.extension_elements) == 1
ee = dr.extension_elements[0]
assert ee.tag == "Transforms"
assert ee.namespace == "http://www.w3.org/2000/09/xmldsig#"
trs = saml2.extension_element_to_element(ee, xmldsig.ELEMENT_FROM_STRING,
namespace=xmldsig.NAMESPACE)
assert trs
assert len(trs.transform) == 1
tr = trs.transform[0]
assert tr.algorithm == "http://www.w3.org/TR/1999/REC-xpath-19991116"
assert len(tr.x_path) == 1
assert tr.x_path[0].text.strip() == """self::xenc:EncryptedData[@Id="example1"]"""

998
tests/test_02_saml.py Normal file
View File

@@ -0,0 +1,998 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Umeå University.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for saml2.saml"""
__author__ = 'roland.hedberg@adm.umu.se (Roland Hedberg)'
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import saml2
import saml2_data, ds_data
import xmldsig as ds
from saml2 import saml
from py.test import raises
class TestNameID:
def setup_class(self):
self.name_id = saml.NameID()
def testEmptyExtensionsList(self):
"""Test if NameID has empty extensions list"""
assert isinstance(self.name_id.extension_elements, list)
assert len(self.name_id.extension_elements) == 0
def testFormatAttribute(self):
"""Test for Format attribute accessors"""
self.name_id.format = saml.NAMEID_FORMAT_EMAILADDRESS
assert self.name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS
assert len(self.name_id.extension_elements) == 0
new_name_id = saml.name_id_from_string(self.name_id.to_string())
assert len(new_name_id.extension_elements) == 0
self.name_id.extension_elements.append(saml2.ExtensionElement(
'foo', text='bar'))
assert len(self.name_id.extension_elements) == 1
assert self.name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS
def testNameIDText(self):
"""Test text value of NameID element"""
self.name_id.text = "tmatsuo@example.com"
assert self.name_id.text == "tmatsuo@example.com"
def testSPProvidedID(self):
"""Test for SPProvidedID attribute accessors"""
self.name_id.sp_provided_id = "provided id"
assert self.name_id.sp_provided_id == "provided id"
def testEmptyNameIDToAndFromStringMatch(self):
"""Test name_id_from_string() with empty NameID"""
string_from_name_id = self.name_id.to_string()
new_name_id = saml.name_id_from_string(string_from_name_id)
string_from_new_name_id = new_name_id.to_string()
assert string_from_name_id == string_from_new_name_id
def testNameIDToAndFromStringMatch(self):
"""Test name_id_from_string() with data"""
self.name_id.format = saml.NAMEID_FORMAT_EMAILADDRESS
self.name_id.text = "tmatsuo@example.com"
self.name_id.name_qualifier = "name_qualifier"
self.name_id.sp_name_qualifier = "sp_name_qualifier"
string_from_name_id = self.name_id.to_string()
new_name_id = saml.name_id_from_string(string_from_name_id)
assert new_name_id.name_qualifier == "name_qualifier"
assert new_name_id.sp_name_qualifier == "sp_name_qualifier"
string_from_new_name_id = new_name_id.to_string()
assert string_from_name_id == string_from_new_name_id
def testExtensionAttributes(self):
"""Test extension attributes"""
self.name_id.extension_attributes['hoge'] = 'fuga'
self.name_id.extension_attributes['moge'] = 'muga'
assert self.name_id.extension_attributes['hoge'] == 'fuga'
assert self.name_id.extension_attributes['moge'] == 'muga'
new_name_id = saml.name_id_from_string(self.name_id.to_string())
assert new_name_id.extension_attributes['hoge'] == 'fuga'
assert new_name_id.extension_attributes['moge'] == 'muga'
def testname_id_from_string(self):
"""Test name_id_from_string() using test data"""
name_id = saml.name_id_from_string(saml2_data.TEST_NAME_ID)
assert name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS
assert name_id.text.strip() == "tmatsuo@example.com"
assert name_id.sp_provided_id == "sp provided id"
class TestIssuer:
def setup_class(self):
self.issuer = saml.Issuer()
def testIssuerToAndFromString(self):
"""Test issuer_from_string()"""
self.issuer.text = "http://www.example.com/test"
self.issuer.name_qualifier = "name_qualifier"
self.issuer.sp_name_qualifier = "sp_name_qualifier"
new_issuer = saml.issuer_from_string(self.issuer.to_string())
assert self.issuer.text == new_issuer.text
assert self.issuer.name_qualifier == new_issuer.name_qualifier
assert self.issuer.sp_name_qualifier == new_issuer.sp_name_qualifier
assert self.issuer.extension_elements == new_issuer.extension_elements
def testUsingTestData(self):
"""Test issuer_from_string() using test data"""
issuer = saml.issuer_from_string(saml2_data.TEST_ISSUER)
assert issuer.text.strip() == "http://www.example.com/test"
new_issuer = saml.issuer_from_string(issuer.to_string())
assert issuer.text == new_issuer.text
assert issuer.extension_elements == new_issuer.extension_elements
class TestSubjectLocality:
def setup_class(self):
self.subject_locality = saml.SubjectLocality()
def testAccessors(self):
"""Test for SubjectLocality accessors"""
self.subject_locality.address = "127.0.0.1"
self.subject_locality.dns_name = "localhost"
assert self.subject_locality.address == "127.0.0.1"
assert self.subject_locality.dns_name == "localhost"
new_subject_locality = saml.subject_locality_from_string(
self.subject_locality.to_string())
assert new_subject_locality.address == "127.0.0.1"
assert new_subject_locality.dns_name == "localhost"
def testUsingTestData(self):
"""Test SubjectLocalityFromString() using test data"""
subject_locality = saml.subject_locality_from_string(
saml2_data.TEST_SUBJECT_LOCALITY)
assert subject_locality.address == "127.0.0.1"
assert subject_locality.dns_name == "localhost"
new_subject_locality = saml.subject_locality_from_string(
subject_locality.to_string())
assert new_subject_locality.address == "127.0.0.1"
assert new_subject_locality.dns_name == "localhost"
assert subject_locality.to_string() == new_subject_locality.to_string()
class TestAuthnContextClassRef:
def setup_class(self):
self.authn_context_class_ref = saml.AuthnContextClassRef()
self.text = "http://www.example.com/authnContextClassRef"
def testAccessors(self):
"""Test for AuthnContextClassRef accessors"""
self.authn_context_class_ref.text = self.text
assert self.authn_context_class_ref.text == self.text
new_authn_context_class_ref = saml.authn_context_class_ref_from_string(
self.authn_context_class_ref.to_string())
assert new_authn_context_class_ref.text == self.text
assert self.authn_context_class_ref.to_string() == \
new_authn_context_class_ref.to_string()
def testUsingTestData(self):
"""Test authn_context_class_ref_from_string() using test data"""
authn_context_class_ref = saml.authn_context_class_ref_from_string(
saml2_data.TEST_AUTHN_CONTEXT_CLASS_REF)
assert authn_context_class_ref.text.strip() == self.text
class TestAuthnContextDeclRef:
def setup_class(self):
self.authn_context_decl_ref = saml.AuthnContextDeclRef()
self.ref = "http://www.example.com/authnContextDeclRef"
def testAccessors(self):
"""Test for AuthnContextDeclRef accessors"""
self.authn_context_decl_ref.text = self.ref
assert self.authn_context_decl_ref.text == self.ref
new_authn_context_decl_ref = saml.authn_context_decl_ref_from_string(
self.authn_context_decl_ref.to_string())
assert new_authn_context_decl_ref.text == self.ref
assert self.authn_context_decl_ref.to_string() == \
new_authn_context_decl_ref.to_string()
def testUsingTestData(self):
"""Test authn_context_decl_ref_from_string() using test data"""
authn_context_decl_ref = saml.authn_context_decl_ref_from_string(
saml2_data.TEST_AUTHN_CONTEXT_DECL_REF)
assert authn_context_decl_ref.text.strip() == self.ref
class TestAuthnContextDecl:
def setup_class(self):
self.authn_context_decl = saml.AuthnContextDecl()
self.text = "http://www.example.com/authnContextDecl"
def testAccessors(self):
"""Test for AuthnContextDecl accessors"""
self.authn_context_decl.text = self.text
assert self.authn_context_decl.text == self.text
new_authn_context_decl = saml.authn_context_decl_from_string(
self.authn_context_decl.to_string())
assert new_authn_context_decl.text == self.text
assert self.authn_context_decl.to_string() == \
new_authn_context_decl.to_string()
def testUsingTestData(self):
"""Test authn_context_decl_from_string() using test data"""
authn_context_decl = saml.authn_context_decl_from_string(
saml2_data.TEST_AUTHN_CONTEXT_DECL)
assert authn_context_decl.text.strip() == self.text
class TestAuthenticatingAuthority:
def setup_class(self):
self.authenticating_authority = saml.AuthenticatingAuthority()
self.text = "http://www.example.com/authenticatingAuthority"
def testAccessors(self):
"""Test for AuthenticatingAuthority accessors"""
self.authenticating_authority.text = self.text
assert self.authenticating_authority.text == self.text
new_authenticating_authority = saml.authenticating_authority_from_string(
self.authenticating_authority.to_string())
assert new_authenticating_authority.text == self.text
assert self.authenticating_authority.to_string() == \
new_authenticating_authority.to_string()
def testUsingTestData(self):
"""Test authenticating_authority_from_string() using test data"""
authenticating_authority = saml.authenticating_authority_from_string(
saml2_data.TEST_AUTHENTICATING_AUTHORITY)
assert authenticating_authority.text.strip() == self.text
class TestAuthnContext:
def setup_class(self):
self.authn_context = saml.AuthnContext()
def testAccessors(self):
"""Test for AuthnContext accessors"""
self.authn_context.authn_context_class_ref = \
saml.authn_context_class_ref_from_string(
saml2_data.TEST_AUTHN_CONTEXT_CLASS_REF)
self.authn_context.authn_context_decl_ref = \
saml.authn_context_decl_ref_from_string(
saml2_data.TEST_AUTHN_CONTEXT_DECL_REF)
self.authn_context.authn_context_decl = \
saml.authn_context_decl_from_string(
saml2_data.TEST_AUTHN_CONTEXT_DECL)
self.authn_context.authenticating_authority.append(
saml.authenticating_authority_from_string(
saml2_data.TEST_AUTHENTICATING_AUTHORITY))
assert self.authn_context.authn_context_class_ref.text.strip() == \
"http://www.example.com/authnContextClassRef"
assert self.authn_context.authn_context_decl_ref.text.strip() == \
"http://www.example.com/authnContextDeclRef"
assert self.authn_context.authn_context_decl.text.strip() == \
"http://www.example.com/authnContextDecl"
assert self.authn_context.authenticating_authority[0].text.strip() == \
"http://www.example.com/authenticatingAuthority"
new_authn_context = saml.authn_context_from_string(
self.authn_context.to_string())
assert self.authn_context.to_string() == new_authn_context.to_string()
def testUsingTestData(self):
"""Test authn_context_from_string() using test data"""
authn_context = saml.authn_context_from_string(saml2_data.TEST_AUTHN_CONTEXT)
assert authn_context.authn_context_class_ref.text.strip() == \
saml.AUTHN_PASSWORD
class TestAuthnStatement:
def setup_class(self):
self.authn_statem = saml.AuthnStatement()
def testAccessors(self):
"""Test for AuthnStatement accessors"""
self.authn_statem.authn_instant = "2007-08-31T01:05:02Z"
self.authn_statem.session_not_on_or_after = "2007-09-14T01:05:02Z"
self.authn_statem.session_index = "sessionindex"
self.authn_statem.authn_context = saml.AuthnContext()
self.authn_statem.authn_context.authn_context_class_ref = \
saml.authn_context_class_ref_from_string(
saml2_data.TEST_AUTHN_CONTEXT_CLASS_REF)
self.authn_statem.authn_context.authn_context_decl_ref = \
saml.authn_context_decl_ref_from_string(
saml2_data.TEST_AUTHN_CONTEXT_DECL_REF)
self.authn_statem.authn_context.authn_context_decl = \
saml.authn_context_decl_from_string(
saml2_data.TEST_AUTHN_CONTEXT_DECL)
self.authn_statem.authn_context.authenticating_authority.append(
saml.authenticating_authority_from_string(
saml2_data.TEST_AUTHENTICATING_AUTHORITY))
new_as = saml.authn_statement_from_string(self.authn_statem.to_string())
assert new_as.authn_instant == "2007-08-31T01:05:02Z"
assert new_as.session_index == "sessionindex"
assert new_as.session_not_on_or_after == "2007-09-14T01:05:02Z"
assert new_as.authn_context.authn_context_class_ref.text.strip() == \
"http://www.example.com/authnContextClassRef"
assert new_as.authn_context.authn_context_decl_ref.text.strip() == \
"http://www.example.com/authnContextDeclRef"
assert new_as.authn_context.authn_context_decl.text.strip() == \
"http://www.example.com/authnContextDecl"
assert new_as.authn_context.authenticating_authority[0].text.strip() \
== "http://www.example.com/authenticatingAuthority"
assert self.authn_statem.to_string() == new_as.to_string()
def testUsingTestData(self):
"""Test authn_statement_from_string() using test data"""
authn_statem = saml.authn_statement_from_string(saml2_data.TEST_AUTHN_STATEMENT)
assert authn_statem.authn_instant == "2007-08-31T01:05:02Z"
assert authn_statem.session_not_on_or_after == "2007-09-14T01:05:02Z"
assert authn_statem.authn_context.authn_context_class_ref.text.strip() == \
saml.AUTHN_PASSWORD
class TestAttributeValue:
def setup_class(self):
self.attribute_value = saml.AttributeValue()
self.text = "value for test attribute"
def testAccessors(self):
"""Test for AttributeValue accessors"""
self.attribute_value.text = self.text
new_attribute_value = saml.attribute_value_from_string(
self.attribute_value.to_string())
assert new_attribute_value.text.strip() == self.text
def testUsingTestData(self):
"""Test attribute_value_from_string() using test data"""
attribute_value = saml.attribute_value_from_string(
saml2_data.TEST_ATTRIBUTE_VALUE)
assert attribute_value.text.strip() == self.text
BASIC_STR_AV = """<?xml version="1.0" encoding="utf-8"?>
<Attribute xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
Name="FirstName">
<AttributeValue xsi:type="xs:string">By-Tor</AttributeValue>
</Attribute>"""
BASIC_INT_AV = """<?xml version="1.0" encoding="utf-8"?>
<Attribute xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
Name="age">
<AttributeValue xsi:type="xs:int">23</AttributeValue>
</Attribute>"""
BASIC_NOT_INT_AV = """<?xml version="1.0" encoding="utf-8"?>
<Attribute xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
Name="age">
<AttributeValue xsi:type="xs:int">foo</AttributeValue>
</Attribute>"""
BASIC_BOOLEAN_TRUE_AV = """<?xml version="1.0" encoding="utf-8"?>
<Attribute xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
Name="on-off">
<AttributeValue xsi:type="xs:boolean">true</AttributeValue>
</Attribute>"""
BASIC_BOOLEAN_FALSE_AV = """<?xml version="1.0" encoding="utf-8"?>
<Attribute xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
Name="on-off">
<AttributeValue xsi:type="xs:boolean">false</AttributeValue>
</Attribute>"""
BASIC_BASE64_AV = """<?xml version="1.0" encoding="utf-8"?>
<Attribute xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
Name="FirstName">
<AttributeValue
xsi:type="xs:base64Binary">VU5JTkVUVA==</AttributeValue>
</Attribute>"""
X500_AV = """<?xml version="1.0" encoding="utf-8"?>
<Attribute xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:x500="urn:oasis:names:tc:SAML:2.0:profiles:attribute:X500"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
Name="urn:oid:2.5.4.42" FriendlyName="givenName">
<AttributeValue xsi:type="xs:string" x500:Encoding="LDAP">Steven
</AttributeValue>
</Attribute>"""
UUID_AV = """<?xml version="1.0" encoding="utf-8"?>
<Attribute xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
Name="urn:uuid:6c9d0ec8-dd2d-11cc-abdd-080009353559"
FriendlyName="pre_auth_req">
<AttributeValue xsi:type="xs:integer">1</AttributeValue>
</Attribute>"""
class TestAttribute:
def setup_class(self):
self.attribute = saml.Attribute()
self.text = ["value of test attribute",
"value1 of test attribute",
"value2 of test attribute"]
def testAccessors(self):
"""Test for Attribute accessors"""
self.attribute.name = "testAttribute"
self.attribute.name_format = saml.NAME_FORMAT_URI
self.attribute.friendly_name = "test attribute"
self.attribute.attribute_value.append(saml.AttributeValue())
self.attribute.attribute_value[0].text = self.text[0]
new_attribute = saml.attribute_from_string(self.attribute.to_string())
assert new_attribute.name == "testAttribute"
assert new_attribute.name_format == saml.NAME_FORMAT_URI
assert new_attribute.friendly_name == "test attribute"
assert new_attribute.attribute_value[0].text.strip() == self.text[0]
def testUsingTestData(self):
"""Test attribute_from_string() using test data"""
attribute = saml.attribute_from_string(saml2_data.TEST_ATTRIBUTE)
assert attribute.name == "testAttribute"
assert attribute.name_format == saml.NAME_FORMAT_UNSPECIFIED
assert attribute.friendly_name == "test attribute"
assert attribute.attribute_value[0].text.strip() == self.text[1]
assert attribute.attribute_value[1].text.strip() == self.text[2]
# test again
attribute = saml.attribute_from_string(attribute.to_string())
assert attribute.name == "testAttribute"
assert attribute.name_format == saml.NAME_FORMAT_UNSPECIFIED
assert attribute.friendly_name == "test attribute"
assert attribute.attribute_value[0].text.strip() == self.text[1]
assert attribute.attribute_value[1].text.strip() == self.text[2]
def test_basic_str(self):
attribute = saml.attribute_from_string(BASIC_STR_AV)
print attribute
assert attribute.attribute_value[0].text.strip() == "By-Tor"
def test_basic_int(self):
attribute = saml.attribute_from_string(BASIC_INT_AV)
print attribute
assert attribute.attribute_value[0].text == "23"
def test_basic_not_int(self):
# attr = saml.attribute_from_string(BASIC_NOT_INT_AV)
# print attr.__dict__.keys()
# print attr.attribute_value[0].__dict__.keys()
# print attr.attribute_value[0].type
# print attr.attribute_value[0].extension_attributes
# print attr
raises(ValueError, "saml.attribute_from_string(BASIC_NOT_INT_AV)")
def test_basic_base64(self):
attribute = saml.attribute_from_string(BASIC_BASE64_AV)
print attribute
assert attribute.attribute_value[0].text == "VU5JTkVUVA=="
assert attribute.attribute_value[0].get_type() == "xs:base64Binary"
def test_basic_boolean_true(self):
attribute = saml.attribute_from_string(BASIC_BOOLEAN_TRUE_AV)
print attribute
assert attribute.attribute_value[0].text.lower() == "true"
def test_basic_boolean_false(self):
attribute = saml.attribute_from_string(BASIC_BOOLEAN_FALSE_AV)
print attribute
assert attribute.attribute_value[0].text.lower() == "false"
class TestAttributeStatement:
def setup_class(self):
self.attr_statem = saml.AttributeStatement()
self.text = ["value of test attribute",
"value1 of test attribute",
"value2 of test attribute",
"value1 of test attribute2",
"value2 of test attribute2",]
def testAccessors(self):
"""Test for Attribute accessors"""
self.attr_statem.attribute.append(saml.Attribute())
self.attr_statem.attribute.append(saml.Attribute())
self.attr_statem.attribute[0].name = "testAttribute"
self.attr_statem.attribute[0].name_format = saml.NAME_FORMAT_URI
self.attr_statem.attribute[0].friendly_name = "test attribute"
self.attr_statem.attribute[0].attribute_value.append(saml.AttributeValue())
self.attr_statem.attribute[0].attribute_value[0].text = self.text[0]
self.attr_statem.attribute[1].name = "testAttribute2"
self.attr_statem.attribute[1].name_format = saml.NAME_FORMAT_UNSPECIFIED
self.attr_statem.attribute[1].friendly_name = self.text[2]
self.attr_statem.attribute[1].attribute_value.append(saml.AttributeValue())
self.attr_statem.attribute[1].attribute_value[0].text = self.text[2]
new_as = saml.attribute_statement_from_string(self.attr_statem.to_string())
assert new_as.attribute[0].name == "testAttribute"
assert new_as.attribute[0].name_format == saml.NAME_FORMAT_URI
assert new_as.attribute[0].friendly_name == "test attribute"
assert new_as.attribute[0].attribute_value[0].text.strip() == self.text[0]
assert new_as.attribute[1].name == "testAttribute2"
assert new_as.attribute[1].name_format == saml.NAME_FORMAT_UNSPECIFIED
assert new_as.attribute[1].friendly_name == "value2 of test attribute"
assert new_as.attribute[1].attribute_value[0].text.strip() == self.text[2]
def testUsingTestData(self):
"""Test attribute_statement_from_string() using test data"""
attr_statem = saml.attribute_statement_from_string( \
saml2_data.TEST_ATTRIBUTE_STATEMENT)
assert attr_statem.attribute[0].name == "testAttribute"
assert attr_statem.attribute[0].name_format == saml.NAME_FORMAT_UNSPECIFIED
assert attr_statem.attribute[0].friendly_name == "test attribute"
assert attr_statem.attribute[0].attribute_value[0].text.strip() == self.text[1]
assert attr_statem.attribute[0].attribute_value[1].text.strip() == self.text[2]
assert attr_statem.attribute[1].name == "http://www.example.com/testAttribute2"
assert attr_statem.attribute[1].name_format == saml.NAME_FORMAT_URI
assert attr_statem.attribute[1].friendly_name == "test attribute2"
assert attr_statem.attribute[1].attribute_value[0].text.strip() == self.text[3]
assert attr_statem.attribute[1].attribute_value[1].text.strip() == self.text[4]
# test again
attr_statem2 = saml.attribute_statement_from_string(attr_statem.to_string())
assert attr_statem2.attribute[0].name == "testAttribute"
assert attr_statem2.attribute[0].name_format == saml.NAME_FORMAT_UNSPECIFIED
assert attr_statem2.attribute[0].friendly_name == "test attribute"
assert attr_statem2.attribute[0].attribute_value[0].text.strip() == self.text[1]
assert attr_statem2.attribute[0].attribute_value[1].text.strip() == self.text[2]
assert attr_statem2.attribute[1].name == "http://www.example.com/testAttribute2"
assert attr_statem2.attribute[1].name_format == saml.NAME_FORMAT_URI
assert attr_statem2.attribute[1].friendly_name == "test attribute2"
assert attr_statem2.attribute[1].attribute_value[0].text.strip() == self.text[3]
assert attr_statem2.attribute[1].attribute_value[1].text.strip() == self.text[4]
class TestSubjectConfirmationData:
def setup_class(self):
self.scd = saml.SubjectConfirmationData()
def testAccessors(self):
"""Test for SubjectConfirmationData accessors"""
self.scd.not_before = "2007-08-31T01:05:02Z"
self.scd.not_on_or_after = "2007-09-14T01:05:02Z"
self.scd.recipient = "recipient"
self.scd.in_response_to = "responseID"
self.scd.address = "127.0.0.1"
new_scd = saml.subject_confirmation_data_from_string(self.scd.to_string())
assert new_scd.not_before == "2007-08-31T01:05:02Z"
assert new_scd.not_on_or_after == "2007-09-14T01:05:02Z"
assert new_scd.recipient == "recipient"
assert new_scd.in_response_to == "responseID"
assert new_scd.address == "127.0.0.1"
def testUsingTestData(self):
"""Test subject_confirmation_data_from_string() using test data"""
scd = saml.subject_confirmation_data_from_string(
saml2_data.TEST_SUBJECT_CONFIRMATION_DATA)
assert scd.not_before == "2007-08-31T01:05:02Z"
assert scd.not_on_or_after == "2007-09-14T01:05:02Z"
assert scd.recipient == "recipient"
assert scd.in_response_to == "responseID"
assert scd.address == "127.0.0.1"
class TestSubjectConfirmation:
def setup_class(self):
self.sc = saml.SubjectConfirmation()
def testAccessors(self):
"""Test for SubjectConfirmation accessors"""
self.sc.name_id = saml.name_id_from_string(saml2_data.TEST_NAME_ID)
self.sc.method = saml.SUBJECT_CONFIRMATION_METHOD_BEARER
self.sc.subject_confirmation_data = saml.subject_confirmation_data_from_string(
saml2_data.TEST_SUBJECT_CONFIRMATION_DATA)
new_sc = saml.subject_confirmation_from_string(self.sc.to_string())
assert new_sc.name_id.sp_provided_id == "sp provided id"
assert new_sc.method == saml.SUBJECT_CONFIRMATION_METHOD_BEARER
assert new_sc.subject_confirmation_data.not_before == \
"2007-08-31T01:05:02Z"
assert new_sc.subject_confirmation_data.not_on_or_after == \
"2007-09-14T01:05:02Z"
assert new_sc.subject_confirmation_data.recipient == "recipient"
assert new_sc.subject_confirmation_data.in_response_to == "responseID"
assert new_sc.subject_confirmation_data.address == "127.0.0.1"
def testUsingTestData(self):
"""Test subject_confirmation_from_string() using test data"""
sc = saml.subject_confirmation_from_string(
saml2_data.TEST_SUBJECT_CONFIRMATION)
assert sc.name_id.sp_provided_id == "sp provided id"
assert sc.method == saml.SUBJECT_CONFIRMATION_METHOD_BEARER
assert sc.subject_confirmation_data.not_before == "2007-08-31T01:05:02Z"
assert sc.subject_confirmation_data.not_on_or_after == "2007-09-14T01:05:02Z"
assert sc.subject_confirmation_data.recipient == "recipient"
assert sc.subject_confirmation_data.in_response_to == "responseID"
assert sc.subject_confirmation_data.address == "127.0.0.1"
class TestSubject:
def setup_class(self):
self.subject = saml.Subject()
def testAccessors(self):
"""Test for Subject accessors"""
self.subject.name_id = saml.name_id_from_string(saml2_data.TEST_NAME_ID)
self.subject.subject_confirmation.append(
saml.subject_confirmation_from_string(
saml2_data.TEST_SUBJECT_CONFIRMATION))
new_subject = saml.subject_from_string(self.subject.to_string())
assert new_subject.name_id.sp_provided_id == "sp provided id"
assert new_subject.name_id.text.strip() == "tmatsuo@example.com"
assert new_subject.name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS
assert isinstance(new_subject.subject_confirmation[0],
saml.SubjectConfirmation)
def testUsingTestData(self):
"""Test for subject_from_string() using test data."""
subject = saml.subject_from_string(saml2_data.TEST_SUBJECT)
assert subject.name_id.sp_provided_id == "sp provided id"
assert subject.name_id.text.strip() == "tmatsuo@example.com"
assert subject.name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS
assert isinstance(subject.subject_confirmation[0],
saml.SubjectConfirmation)
class TestCondition:
def setup_class(self):
self.condition = saml.Condition()
self.name = "{%s}type" % saml.XSI_NAMESPACE
def testAccessors(self):
"""Test for Condition accessors."""
self.condition.extension_attributes[self.name] = "test"
self.condition.extension_attributes['ExtendedAttribute'] = "value"
new_condition = saml.condition_from_string(self.condition.to_string())
assert new_condition.extension_attributes[self.name] == "test"
assert new_condition.extension_attributes["ExtendedAttribute"] == "value"
def testUsingTestData(self):
"""Test for condition_from_string() using test data."""
condition = saml.condition_from_string(saml2_data.TEST_CONDITION)
assert condition.extension_attributes[self.name] == "test"
assert condition.extension_attributes["ExtendedAttribute"] == "value"
class TestAudience:
def setup_class(self):
self.audience = saml.Audience()
def testAccessors(self):
"""Test for Audience accessors"""
self.audience.text = "http://www.example.com/Audience"
new_audience = saml.audience_from_string(self.audience.to_string())
assert new_audience.text.strip() == "http://www.example.com/Audience"
def testUsingTestData(self):
"""Test audience_from_string using test data"""
audience = saml.audience_from_string(saml2_data.TEST_AUDIENCE)
assert audience.text.strip() == "http://www.example.com/Audience"
class TestAudienceRestriction:
def setup_class(self):
self.audience_restriction = saml.AudienceRestriction()
def testAccessors(self):
"""Test for AudienceRestriction accessors"""
self.audience_restriction.audience = \
saml.audience_from_string(saml2_data.TEST_AUDIENCE)
new_audience = saml.audience_restriction_from_string(
self.audience_restriction.to_string())
assert self.audience_restriction.audience.text.strip() == \
"http://www.example.com/Audience"
def testUsingTestData(self):
"""Test audience_restriction_from_string using test data"""
audience_restriction = saml.audience_restriction_from_string(
saml2_data.TEST_AUDIENCE_RESTRICTION)
assert audience_restriction.audience[0].text.strip() == \
"http://www.example.com/Audience"
class TestOneTimeUse:
def setup_class(self):
self.one_time_use = saml.OneTimeUse()
def testAccessors(self):
"""Test for OneTimeUse accessors"""
assert isinstance(self.one_time_use, saml.OneTimeUse)
assert isinstance(self.one_time_use, saml.ConditionAbstractType)
def testUsingTestData(self):
"""Test one_time_use_from_string() using test data"""
one_time_use = saml.one_time_use_from_string(saml2_data.TEST_ONE_TIME_USE)
assert isinstance(one_time_use, saml.OneTimeUse)
assert isinstance(one_time_use, saml.ConditionAbstractType)
class TestProxyRestriction:
def setup_class(self):
self.proxy_restriction = saml.ProxyRestriction()
def testAccessors(self):
"""Test for ProxyRestriction accessors"""
assert isinstance(self.proxy_restriction, saml.ConditionAbstractType)
self.proxy_restriction.count = "2"
self.proxy_restriction.audience.append(saml.audience_from_string(
saml2_data.TEST_AUDIENCE))
new_proxy_restriction = saml.proxy_restriction_from_string(
self.proxy_restriction.to_string())
assert new_proxy_restriction.count == "2"
assert new_proxy_restriction.audience[0].text.strip() == \
"http://www.example.com/Audience"
def testUsingTestData(self):
"""Test proxy_restriction_from_string() using test data"""
proxy_restriction = saml.proxy_restriction_from_string(
saml2_data.TEST_PROXY_RESTRICTION)
assert proxy_restriction.count == "2"
assert proxy_restriction.audience[0].text.strip() == \
"http://www.example.com/Audience"
class TestConditions:
def setup_class(self):
self.conditions = saml.Conditions()
def testAccessors(self):
"""Test for Conditions accessors"""
self.conditions.not_before = "2007-08-31T01:05:02Z"
self.conditions.not_on_or_after = "2007-09-14T01:05:02Z"
self.conditions.condition.append(saml.Condition())
self.conditions.audience_restriction.append(saml.AudienceRestriction())
self.conditions.one_time_use.append(saml.OneTimeUse())
self.conditions.proxy_restriction.append(saml.ProxyRestriction())
new_conditions = saml.conditions_from_string(self.conditions.to_string())
assert new_conditions.not_before == "2007-08-31T01:05:02Z"
assert new_conditions.not_on_or_after == "2007-09-14T01:05:02Z"
assert isinstance(new_conditions.condition[0], saml.Condition)
assert isinstance(new_conditions.audience_restriction[0],
saml.AudienceRestriction)
assert isinstance(new_conditions.one_time_use[0],
saml.OneTimeUse)
assert isinstance(new_conditions.proxy_restriction[0],
saml.ProxyRestriction)
def testUsingTestData(self):
"""Test conditions_from_string() using test data"""
new_conditions = saml.conditions_from_string(saml2_data.TEST_CONDITIONS)
assert new_conditions.not_before == "2007-08-31T01:05:02Z"
assert new_conditions.not_on_or_after == "2007-09-14T01:05:02Z"
assert isinstance(new_conditions.condition[0], saml.Condition)
assert isinstance(new_conditions.audience_restriction[0],
saml.AudienceRestriction)
assert isinstance(new_conditions.one_time_use[0],
saml.OneTimeUse)
assert isinstance(new_conditions.proxy_restriction[0],
saml.ProxyRestriction)
class TestAssertionIDRef:
def setup_class(self):
self.assertion_id_ref = saml.AssertionIDRef()
def testAccessors(self):
"""Test for AssertionIDRef accessors"""
self.assertion_id_ref.text = "zzlieajngjbkjggjldmgindkckkolcblndbghlhm"
new_assertion_id_ref = saml.assertion_id_ref_from_string(
self.assertion_id_ref.to_string())
assert new_assertion_id_ref.text == \
"zzlieajngjbkjggjldmgindkckkolcblndbghlhm"
def testUsingTestData(self):
"""Test assertion_id_ref_from_string() using test data"""
new_assertion_id_ref = saml.assertion_id_ref_from_string(
saml2_data.TEST_ASSERTION_ID_REF)
assert new_assertion_id_ref.text.strip() == \
"zzlieajngjbkjggjldmgindkckkolcblndbghlhm"
class TestAssertionURIRef:
def setup_class(self):
self.assertion_uri_ref = saml.AssertionURIRef()
def testAccessors(self):
"""Test for AssertionURIRef accessors"""
self.assertion_uri_ref.text = "http://www.example.com/AssertionURIRef"
new_assertion_uri_ref = saml.assertion_uri_ref_from_string(
self.assertion_uri_ref.to_string())
assert new_assertion_uri_ref.text == \
"http://www.example.com/AssertionURIRef"
def testUsingTestData(self):
"""Test assertion_uri_ref_from_string() using test data"""
new_assertion_uri_ref = saml.assertion_uri_ref_from_string(
saml2_data.TEST_ASSERTION_URI_REF)
assert new_assertion_uri_ref.text.strip() == \
"http://www.example.com/AssertionURIRef"
class TestAction:
def setup_class(self):
self.action = saml.Action()
def testAccessors(self):
"""Test for Action accessors"""
self.action.namespace = "http://www.example.com/Namespace"
new_action = saml.action_from_string(self.action.to_string())
assert new_action.namespace == "http://www.example.com/Namespace"
def testUsingTestData(self):
"""Test action_from_string() using test data"""
new_action = saml.action_from_string(saml2_data.TEST_ACTION)
assert new_action.namespace == "http://www.example.com/Namespace"
class TestEvidence:
def setup_class(self):
self.evidence = saml.Evidence()
def testAccessors(self):
"""Test for Evidence accessors"""
self.evidence.assertion_id_ref.append(saml.AssertionIDRef())
self.evidence.assertion_uri_ref.append(saml.AssertionURIRef())
self.evidence.assertion.append(saml.Assertion())
self.evidence.encrypted_assertion.append(saml.EncryptedAssertion())
new_evidence = saml.evidence_from_string(self.evidence.to_string())
print new_evidence
assert self.evidence.to_string() == new_evidence.to_string()
assert isinstance(new_evidence.assertion_id_ref[0],
saml.AssertionIDRef)
assert isinstance(new_evidence.assertion_uri_ref[0],
saml.AssertionURIRef)
assert len(new_evidence.assertion) == 1
assert isinstance(new_evidence.assertion[0], saml.Assertion)
assert len(new_evidence.encrypted_assertion) == 1
assert isinstance(new_evidence.encrypted_assertion[0],
saml.EncryptedAssertion)
def testUsingTestData(self):
"""Test evidence_from_string() using test data"""
# TODO:
pass
class TestAuthzDecisionStatement:
def setup_class(self):
self.authz_decision_statement = saml.AuthzDecisionStatement()
def testAccessors(self):
"""Test for AuthzDecisionStatement accessors"""
self.authz_decision_statement.resource = "http://www.example.com/Resource"
self.authz_decision_statement.decision = saml.DECISION_TYPE_PERMIT
self.authz_decision_statement.action.append(saml.Action())
self.authz_decision_statement.evidence = saml.Evidence()
new_authz_decision_statement = saml.authz_decision_statement_from_string(
self.authz_decision_statement.to_string())
assert self.authz_decision_statement.to_string() == \
new_authz_decision_statement.to_string()
assert new_authz_decision_statement.resource == \
"http://www.example.com/Resource"
assert new_authz_decision_statement.decision == \
saml.DECISION_TYPE_PERMIT
assert isinstance(new_authz_decision_statement.action[0],
saml.Action)
assert isinstance(new_authz_decision_statement.evidence,
saml.Evidence)
def testUsingTestData(self):
"""Test authz_decision_statement_from_string() using test data"""
# TODO:
pass
class TestAdvice:
def setup_class(self):
self.advice = saml.Advice()
def testAccessors(self):
"""Test for Advice accessors"""
self.advice.assertion_id_ref.append(saml.AssertionIDRef())
self.advice.assertion_uri_ref.append(saml.AssertionURIRef())
self.advice.assertion.append(saml.Assertion())
self.advice.encrypted_assertion.append(saml.EncryptedAssertion())
new_advice = saml.advice_from_string(self.advice.to_string())
assert self.advice.to_string() == new_advice.to_string()
assert isinstance(new_advice.assertion_id_ref[0],
saml.AssertionIDRef)
assert isinstance(new_advice.assertion_uri_ref[0],
saml.AssertionURIRef)
assert isinstance(new_advice.assertion[0], saml.Assertion)
assert isinstance(new_advice.encrypted_assertion[0],
saml.EncryptedAssertion)
def testUsingTestData(self):
"""Test advice_from_string() using test data"""
# TODO:
pass
class TestAssertion:
def setup_class(self):
self.assertion = saml.Assertion()
def testAccessors(self):
"""Test for Assertion accessors"""
self.assertion.id = "assertion id"
self.assertion.version = saml2.VERSION
self.assertion.issue_instant = "2007-08-31T01:05:02Z"
self.assertion.issuer = saml.issuer_from_string(saml2_data.TEST_ISSUER)
self.assertion.signature = ds.signature_from_string(
ds_data.TEST_SIGNATURE)
self.assertion.subject = saml.subject_from_string(saml2_data.TEST_SUBJECT)
self.assertion.conditions = saml.conditions_from_string(
saml2_data.TEST_CONDITIONS)
self.assertion.advice = saml.Advice()
self.assertion.statement.append(saml.Statement())
self.assertion.authn_statement.append(saml.authn_statement_from_string(
saml2_data.TEST_AUTHN_STATEMENT))
self.assertion.authz_decision_statement.append(
saml.AuthzDecisionStatement())
self.assertion.attribute_statement.append(
saml.attribute_statement_from_string(
saml2_data.TEST_ATTRIBUTE_STATEMENT))
new_assertion = saml.assertion_from_string(self.assertion.to_string())
assert new_assertion.id == "assertion id"
assert new_assertion.version == saml2.VERSION
assert new_assertion.issue_instant == "2007-08-31T01:05:02Z"
assert isinstance(new_assertion.issuer, saml.Issuer)
assert isinstance(new_assertion.signature, ds.Signature)
assert isinstance(new_assertion.subject, saml.Subject)
assert isinstance(new_assertion.conditions, saml.Conditions)
assert isinstance(new_assertion.advice, saml.Advice)
assert isinstance(new_assertion.statement[0], saml.Statement)
assert isinstance(new_assertion.authn_statement[0],
saml.AuthnStatement)
assert isinstance(new_assertion.authz_decision_statement[0],
saml.AuthzDecisionStatement)
assert isinstance(new_assertion.attribute_statement[0],
saml.AttributeStatement)
def testUsingTestData(self):
"""Test assertion_from_string() using test data"""
# TODO
pass

524
tests/test_03_saml2.py Normal file
View File

@@ -0,0 +1,524 @@
#!/usr/bin/env python
import saml2
from saml2 import create_class_from_xml_string, class_name, make_vals, md
from saml2.saml import NameID, Issuer, SubjectLocality, AuthnContextClassRef
from saml2.saml import SubjectConfirmationData, SubjectConfirmation
from saml2.saml import Attribute
from py.test import raises
import saml2_data
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
from elementtree import ElementTree
ITEMS = {
NameID:["""<?xml version="1.0" encoding="utf-8"?>
<NameID xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
SPProvidedID="sp provided id">
roland@example.com
</NameID>
""", """<?xml version="1.0" encoding="utf-8"?>
<NameID xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
SPNameQualifier="https://foo.example.com/sp"
Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">_1632879f09d08ea5ede2dc667cbed7e429ebc4335c</NameID>
""", """<?xml version="1.0" encoding="utf-8"?>
<NameID xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
NameQualifier="http://authentic.example.com/saml/metadata"
SPNameQualifier="http://auth.example.com/saml/metadata">test
</NameID>"""],
Issuer:"""<?xml version="1.0" encoding="utf-8"?>
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
http://www.example.com/test
</Issuer>
""",
SubjectLocality: """<?xml version="1.0" encoding="utf-8"?>
<SubjectLocality xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
Address="127.0.0.1" DNSName="localhost"/>
""",
SubjectConfirmationData:
"""<?xml version="1.0" encoding="utf-8"?>
<SubjectConfirmationData xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
InResponseTo="_1683146e27983964fbe7bf8f08961108d166a652e5"
NotOnOrAfter="2010-02-18T13:52:13.959Z"
NotBefore="2010-01-16T12:00:00Z"
Recipient="http://192.168.0.10/saml/sp" />""",
SubjectConfirmation:
"""<?xml version="1.0" encoding="utf-8"?>
<SubjectConfirmation xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><NameID
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
NameQualifier="http://authentic.example.com/saml/metadata">test@example.com
</NameID>
<SubjectConfirmationData
NotOnOrAfter="2010-02-17T17:02:38Z"
Recipient="http://auth.example.com/saml/proxySingleSignOnRedirect"
InResponseTo="_59B3A01B03334032C31E434C63F89E3E"/></SubjectConfirmation>"""
}
#def pytest_generate_tests(metafunc):
# if "target_class" in metafunc.funcargnames:
# for tcl,xml in ITEMS.items():
# metafunc.addcall(funcargs={"target_class":tcl,"xml_string":xml})
def _eq(l1,l2):
return set(l1) == set(l2)
def test_create_class_from_xml_string_nameid():
kl = create_class_from_xml_string(NameID, ITEMS[NameID][0])
assert kl != None
assert kl.format == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
assert kl.sp_provided_id == "sp provided id"
assert kl.text.strip() == "roland@example.com"
assert _eq(kl.keyswv(), ['sp_provided_id', 'format', 'text'])
assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:NameID"
assert _eq(kl.keys(), ['sp_provided_id', 'sp_name_qualifier',
'name_qualifier', 'format', 'text'])
kl = create_class_from_xml_string(NameID, ITEMS[NameID][1])
assert kl != None
assert kl.format == "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"
assert kl.sp_name_qualifier == "https://foo.example.com/sp"
assert kl.text.strip() == "_1632879f09d08ea5ede2dc667cbed7e429ebc4335c"
assert _eq(kl.keyswv(), ['sp_name_qualifier', 'format', 'text'])
assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:NameID"
kl = create_class_from_xml_string(NameID, ITEMS[NameID][2])
assert kl != None
assert kl.format == "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
assert kl.name_qualifier == "http://authentic.example.com/saml/metadata"
assert kl.sp_name_qualifier == "http://auth.example.com/saml/metadata"
assert kl.text.strip() == "test"
assert _eq(kl.keyswv(), ['sp_name_qualifier', 'format', 'name_qualifier',
'text'])
assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:NameID"
def test_create_class_from_xml_string_issuer():
kl = create_class_from_xml_string(Issuer, ITEMS[Issuer])
assert kl != None
assert kl.text.strip() == "http://www.example.com/test"
assert _eq(kl.keyswv(), ['text'])
assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:Issuer"
def test_create_class_from_xml_string_subject_locality():
kl = create_class_from_xml_string(SubjectLocality, ITEMS[SubjectLocality])
assert kl != None
assert _eq(kl.keyswv(), ['address', "dns_name"])
assert kl.address == "127.0.0.1"
assert kl.dns_name == "localhost"
assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality"
def test_create_class_from_xml_string_subject_confirmation_data():
kl = create_class_from_xml_string(SubjectConfirmationData,
ITEMS[SubjectConfirmationData])
assert kl != None
assert _eq(kl.keyswv(), ['in_response_to', 'not_on_or_after',
'not_before', 'recipient'])
assert kl.in_response_to == "_1683146e27983964fbe7bf8f08961108d166a652e5"
assert kl.not_on_or_after == "2010-02-18T13:52:13.959Z"
assert kl.not_before == "2010-01-16T12:00:00Z"
assert kl.recipient == "http://192.168.0.10/saml/sp"
assert class_name(kl) == \
"urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData"
def test_create_class_from_xml_string_subject_confirmation():
kl = create_class_from_xml_string(SubjectConfirmation,
ITEMS[SubjectConfirmation])
assert kl != None
assert _eq(kl.keyswv(), ['method', 'name_id',
'subject_confirmation_data'])
assert kl.method == "urn:oasis:names:tc:SAML:2.0:cm:bearer"
name_id = kl.name_id
assert _eq(name_id.keyswv(), ['format', 'name_qualifier', 'text'])
assert name_id.format == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
assert name_id.name_qualifier == "http://authentic.example.com/saml/metadata"
assert name_id.text.strip() == "test@example.com"
subject_confirmation_data = kl.subject_confirmation_data
assert _eq(subject_confirmation_data.keyswv(), ['not_on_or_after',
'recipient', 'in_response_to'])
assert subject_confirmation_data.recipient == \
"http://auth.example.com/saml/proxySingleSignOnRedirect"
assert subject_confirmation_data.not_on_or_after == "2010-02-17T17:02:38Z"
assert subject_confirmation_data.in_response_to == \
"_59B3A01B03334032C31E434C63F89E3E"
assert class_name(kl) == \
"urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation"
def test_create_class_from_xml_string_wrong_class_spec():
kl = create_class_from_xml_string(SubjectConfirmationData,
ITEMS[SubjectConfirmation])
assert kl == None
def test_ee_1():
ee = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?><foo>bar</foo>""")
assert ee != None
print ee.__dict__
assert ee.attributes == {}
assert ee.tag == "foo"
assert ee.namespace == None
assert ee.children == []
assert ee.text == "bar"
def test_ee_2():
ee = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?><foo id="xyz">bar</foo>""")
assert ee != None
print ee.__dict__
assert ee.attributes == {"id":"xyz"}
assert ee.tag == "foo"
assert ee.namespace == None
assert ee.children == []
assert ee.text == "bar"
def test_ee_3():
ee = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?>
<foo xmlns="urn:mace:example.com:saml:ns"
id="xyz">bar</foo>""")
assert ee != None
print ee.__dict__
assert ee.attributes == {"id":"xyz"}
assert ee.tag == "foo"
assert ee.namespace == "urn:mace:example.com:saml:ns"
assert ee.children == []
assert ee.text == "bar"
def test_ee_4():
ee = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?>
<foo xmlns="urn:mace:example.com:saml:ns">
<id>xyz</id><bar>tre</bar></foo>""")
assert ee != None
print ee.__dict__
assert ee.attributes == {}
assert ee.tag == "foo"
assert ee.namespace == "urn:mace:example.com:saml:ns"
assert len(ee.children) == 2
assert ee.text.strip() == ""
id = ee.find_children("id", "urn:mace:example.com:saml:namespace")
assert id == []
ids = ee.find_children("id", "urn:mace:example.com:saml:ns")
assert ids != []
id = ids[0]
print id.__dict__
assert id.attributes == {}
assert id.tag == "id"
assert id.namespace == "urn:mace:example.com:saml:ns"
assert id.children == []
assert id.text.strip() == "xyz"
def test_ee_5():
ee = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?>
<foo xmlns="urn:mace:example.com:saml:ns">bar</foo>""")
ce = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?>
<educause xmlns="urn:mace:example.com:saml:cu">rev</educause>""")
ee.children.append(ce)
assert ee != None
print ee.__dict__
assert ee.attributes == {}
assert ee.tag == "foo"
assert ee.namespace == "urn:mace:example.com:saml:ns"
assert len(ee.children) == 1
assert ee.text.strip() == "bar"
c = ee.children[0]
print c.__dict__
child = ee.find_children(namespace="urn:mace:example.com:saml:cu")
assert len(child) == 1
child = ee.find_children(namespace="urn:mace:example.com:saml:ns")
assert len(child) == 0
child = ee.find_children("educause","urn:mace:example.com:saml:cu")
assert len(child) == 1
child = ee.find_children("edugain","urn:mace:example.com:saml:cu")
assert len(child) == 0
print ee.to_string()
def test_ee_6():
ee = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?>
<foo xmlns="urn:mace:example.com:saml:ns">bar</foo>""")
ce = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?>
<educause xmlns="urn:mace:example.com:saml:cu">rev</educause>""")
et = ee.transfer_to_element_tree()
ce.become_child_element_of(et)
pee = saml2._extension_element_from_element_tree(et)
assert pee != None
print pee.__dict__
assert pee.attributes == {}
assert pee.tag == "foo"
assert pee.namespace == "urn:mace:example.com:saml:ns"
assert len(pee.children) == 1
assert pee.text.strip() == "bar"
c = pee.children[0]
print c.__dict__
child = pee.find_children(namespace="urn:mace:example.com:saml:cu")
assert len(child) == 1
child = pee.find_children(namespace="urn:mace:example.com:saml:ns")
assert len(child) == 0
child = pee.find_children("educause","urn:mace:example.com:saml:cu")
assert len(child) == 1
child = pee.find_children("edugain","urn:mace:example.com:saml:cu")
assert len(child) == 0
print pee.to_string()
NAMEID_WITH_ATTRIBUTE_EXTENSION = """<?xml version="1.0" encoding="utf-8"?>
<NameID xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:local="urn:mace:example.com:saml:assertion"
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
SPProvidedID="sp provided id"
local:Foo="BAR">
roland@example.com
</NameID>
"""
def test_nameid_with_extension():
kl = create_class_from_xml_string(NameID, NAMEID_WITH_ATTRIBUTE_EXTENSION)
assert kl != None
print kl.__dict__
assert kl.format == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
assert kl.sp_provided_id == "sp provided id"
assert kl.text.strip() == "roland@example.com"
assert _eq(kl.keyswv(), ['sp_provided_id', 'format',
'extension_attributes', 'text'])
assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:NameID"
assert _eq(kl.keys(), ['sp_provided_id', 'sp_name_qualifier',
'name_qualifier', 'format', 'text'])
assert kl.extension_attributes == {
'{urn:mace:example.com:saml:assertion}Foo': 'BAR'}
SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION = """<?xml version="1.0" encoding="utf-8"?>
<SubjectConfirmation xmlns="urn:oasis:names:tc:SAML:2.0:assertion"
Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<NameID
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
NameQualifier="http://authentic.example.com/saml/metadata">test@example.com
</NameID>
<SubjectConfirmationData
NotOnOrAfter="2010-02-17T17:02:38Z"
Recipient="http://auth.example.com/saml/proxySingleSignOnRedirect"
InResponseTo="_59B3A01B03334032C31E434C63F89E3E"/>
<local:Trustlevel xmlns:local="urn:mace:example.com:saml:assertion">
Excellent
</local:Trustlevel>
</SubjectConfirmation>"""
def test_subject_confirmation_with_extension():
kl = create_class_from_xml_string(SubjectConfirmation,
SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION)
assert kl != None
print kl.__dict__
assert kl.extension_attributes == {}
assert kl.method == "urn:oasis:names:tc:SAML:2.0:cm:bearer"
name_id = kl.name_id
assert _eq(name_id.keyswv(), ['format', 'name_qualifier', 'text'])
assert name_id.format == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
assert name_id.name_qualifier == "http://authentic.example.com/saml/metadata"
assert name_id.text.strip() == "test@example.com"
subject_confirmation_data = kl.subject_confirmation_data
assert _eq(subject_confirmation_data.keyswv(), ['not_on_or_after',
'recipient', 'in_response_to'])
assert subject_confirmation_data.recipient == \
"http://auth.example.com/saml/proxySingleSignOnRedirect"
assert subject_confirmation_data.not_on_or_after == "2010-02-17T17:02:38Z"
assert subject_confirmation_data.in_response_to == \
"_59B3A01B03334032C31E434C63F89E3E"
assert len(kl.extension_elements) == 1
ee = kl.extension_elements[0]
assert ee.tag == "Trustlevel"
assert ee.namespace == "urn:mace:example.com:saml:assertion"
assert ee.text.strip() == "Excellent"
def test_to_fro_string_1():
kl = create_class_from_xml_string(SubjectConfirmation,
SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION)
str = kl.to_string()
cpy = create_class_from_xml_string(SubjectConfirmation, str)
print kl.__dict__
print cpy.__dict__
assert kl.text.strip() == cpy.text.strip()
assert _eq(kl.keyswv(), cpy.keyswv())
assert len(kl.extension_elements) == len(cpy.extension_elements)
klee = kl.extension_elements[0]
cpyee = cpy.extension_elements[0]
assert klee.text.strip() == cpyee.text.strip()
assert klee.tag == cpyee.tag
assert klee.namespace == cpyee.namespace
def test_make_vals_str():
kl = make_vals("Jeter",md.GivenName, part=True)
assert isinstance(kl, md.GivenName)
assert kl.text == "Jeter"
def test_make_vals_list_of_strs():
cp = md.ContactPerson()
make_vals(["Derek","Sanderson"], md.GivenName, cp, "given_name")
assert len(cp.given_name) == 2
assert _eq([i.text for i in cp.given_name],["Sanderson","Derek"])
def test_attribute_element_to_extension_element():
attr = create_class_from_xml_string(Attribute, saml2_data.TEST_ATTRIBUTE)
ee = saml2.element_to_extension_element(attr)
print ee.__dict__
assert ee.tag == "Attribute"
assert ee.namespace == 'urn:oasis:names:tc:SAML:2.0:assertion'
assert _eq(ee.attributes.keys(),['FriendlyName', 'Name', 'NameFormat'])
assert ee.attributes["FriendlyName"] == 'test attribute'
assert ee.attributes["Name"] == "testAttribute"
assert ee.attributes["NameFormat"] == \
'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified'
assert len(ee.children) == 2
for child in ee.children:
# children are also extension element instances
assert child.namespace == 'urn:oasis:names:tc:SAML:2.0:assertion'
assert child.tag == "AttributeValue"
def test_ee_7():
ee = saml2.extension_element_from_string(
"""<?xml version='1.0' encoding='UTF-8'?>
<ExternalEntityAttributeAuthority
xmlns="urn:oasis:names:tc:SAML:metadata:dynamicsaml">
<AssertingEntity>
<NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">
http://federationX.org
</NameID>
</AssertingEntity>
<RetrievalEndpoint>
https://federationX.org/?ID=a87s76a5765da76576a57as
</RetrievalEndpoint>
</ExternalEntityAttributeAuthority>
""")
print ee.__dict__
assert len(ee.children) == 2
for child in ee.children:
assert child.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml"
assert _eq(["AssertingEntity","RetrievalEndpoint"],
[c.tag for c in ee.children])
aes = [c for c in ee.children if c.tag == "AssertingEntity"]
assert len(aes) == 1
assert len(aes[0].children) == 1
assert _eq(aes[0].attributes.keys(),[])
nid = aes[0].children[0]
assert nid.tag == "NameID"
assert nid.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml"
assert len(nid.children) == 0
assert _eq(nid.attributes.keys(),["Format"])
assert nid.text.strip() == "http://federationX.org"
def test_extension_element_loadd():
ava = {'attributes': {},
'tag': 'ExternalEntityAttributeAuthority',
'namespace': 'urn:oasis:names:tc:SAML:metadata:dynamicsaml',
'children': [{
"tag": "AssertingEntity",
"namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml",
"children": [{
"tag":"NameID",
"namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml",
"text": "http://federationX.org",
"attributes":{
"Format":"urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
},
}]
}, {
"tag":"RetrievalEndpoint",
"namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml",
"text":"https://federationX.org/?ID=a87s76a5765da76576a57as",
}],
}
ee = saml2.ExtensionElement(ava["tag"]).loadd(ava)
print ee.__dict__
assert len(ee.children) == 2
for child in ee.children:
assert child.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml"
assert _eq(["AssertingEntity","RetrievalEndpoint"],
[c.tag for c in ee.children])
aes = [c for c in ee.children if c.tag == "AssertingEntity"]
assert len(aes) == 1
assert len(aes[0].children) == 1
assert _eq(aes[0].attributes.keys(),[])
nid = aes[0].children[0]
assert nid.tag == "NameID"
assert nid.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml"
assert len(nid.children) == 0
assert _eq(nid.attributes.keys(),["Format"])
assert nid.text.strip() == "http://federationX.org"
def test_extensions_loadd():
ava = {"extension_elements":[{'attributes': {},
'tag': 'ExternalEntityAttributeAuthority',
'namespace': 'urn:oasis:names:tc:SAML:metadata:dynamicsaml',
'children': [{
"tag": "AssertingEntity",
"namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml",
"children": [{
"tag":"NameID",
"namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml",
"text": "http://federationX.org",
"attributes":{
"Format":"urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
},
}]
}, {
"tag":"RetrievalEndpoint",
"namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml",
"text":"https://federationX.org/?ID=a87s76a5765da76576a57as",
}],
}],
"extension_attributes": {
"foo":"bar",
}
}
extension = saml2.SamlBase()
extension.loadd(ava)
print extension.__dict__
assert len(extension.extension_elements) == 1
ee = extension.extension_elements[0]
assert len(ee.children) == 2
for child in ee.children:
assert child.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml"
assert _eq(["AssertingEntity","RetrievalEndpoint"],
[c.tag for c in ee.children])
aes = [c for c in ee.children if c.tag == "AssertingEntity"]
assert len(aes) == 1
assert len(aes[0].children) == 1
assert _eq(aes[0].attributes.keys(),[])
nid = aes[0].children[0]
assert nid.tag == "NameID"
assert nid.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml"
assert len(nid.children) == 0
assert _eq(nid.attributes.keys(),["Format"])
assert nid.text.strip() == "http://federationX.org"
assert extension.extension_attributes.keys() == ["foo"]
assert extension.extension_attributes["foo"] == "bar"

538
tests/test_04_samlp.py Normal file
View File

@@ -0,0 +1,538 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Umeå University.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for saml2.samlp"""
__author__ = 'roland.hedberg@adm.umu.se (Roland Hedberg)'
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import saml2
import saml2_data, ds_data, samlp_data
from saml2 import saml
from saml2 import samlp
import xmldsig as ds
class TestRequestAbstractType:
def setup_class(self):
self.ar = samlp.RequestAbstractType()
def testAccessors(self):
"""Test for RequestAbstractType accessors"""
self.ar.id = "request id"
self.ar.version = saml2.VERSION
self.ar.issue_instant = "2007-09-14T01:05:02Z"
self.ar.destination = "http://www.example.com/Destination"
self.ar.consent = saml.CONSENT_UNSPECIFIED
self.ar.issuer = saml.Issuer()
self.ar.signature = ds.Signature()
self.ar.extensions = samlp.Extensions()
new_ar = samlp.request_abstract_type_from_string(self.ar.to_string())
assert new_ar.id == "request id"
assert new_ar.version == saml2.VERSION
assert new_ar.issue_instant == "2007-09-14T01:05:02Z"
assert new_ar.destination == "http://www.example.com/Destination"
assert new_ar.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_ar.issuer, saml.Issuer)
assert isinstance(new_ar.signature, ds.Signature)
assert isinstance(new_ar.extensions, samlp.Extensions)
def testUsingTestData(self):
"""Test for request_abstract_type_from_string() using test data"""
# TODO:
pass
class TestStatusDetail:
def setup_class(self):
self.status_detail = samlp.StatusDetail()
def testAccessors(self):
"""Test for StatusDetail accessors"""
# TODO:
pass
class TestStatusMessage:
def setup_class(self):
self.status_message = samlp.StatusMessage()
def testAccessors(self):
"""Test for StatusMessage accessors"""
# TODO:
pass
class TestStatusCode:
def setup_class(self):
self.status_code = samlp.StatusCode()
def testAccessors(self):
"""Test for StatusCode accessors"""
self.status_code.value = samlp.STATUS_RESPONDER
self.status_code.status_code = samlp.StatusCode(
value=samlp.STATUS_REQUEST_DENIED)
print self.status_code.__dict__
new_status_code = samlp.status_code_from_string(self.status_code.to_string())
assert new_status_code.value == samlp.STATUS_RESPONDER
assert new_status_code.status_code.value == \
samlp.STATUS_REQUEST_DENIED
def testUsingTestData(self):
"""Test for status_code_from_string() using test data"""
new_status_code = samlp.status_code_from_string(
samlp_data.TEST_STATUS_CODE)
assert new_status_code.value == samlp.STATUS_RESPONDER
assert new_status_code.status_code.value == \
samlp.STATUS_REQUEST_DENIED
class TestStatus:
def setup_class(self):
self.status = samlp.Status()
def testAccessors(self):
"""Test for Status accessors"""
self.status.status_code = samlp.StatusCode()
self.status.status_message = samlp.StatusMessage()
self.status.status_detail = samlp.StatusDetail()
new_status = samlp.status_from_string(self.status.to_string())
assert isinstance(new_status.status_code, samlp.StatusCode)
assert isinstance(new_status.status_message, samlp.StatusMessage)
assert isinstance(new_status.status_detail, samlp.StatusDetail)
def testUsingTestData(self):
"""Test for status_from_string using test data"""
new_status = samlp.status_from_string(samlp_data.TEST_STATUS)
assert isinstance(new_status.status_code, samlp.StatusCode)
assert isinstance(new_status.status_code.status_code,
samlp.StatusCode)
assert isinstance(new_status.status_message, samlp.StatusMessage)
assert isinstance(new_status.status_detail, samlp.StatusDetail)
class TestStatusResponseType:
def setup_class(self):
self.sr = samlp.StatusResponseType()
def testAccessors(self):
"""Test for StatusResponseType accessors"""
self.sr.id = "response id"
self.sr.in_response_to = "request id"
self.sr.version = saml2.VERSION
self.sr.issue_instant = "2007-09-14T01:05:02Z"
self.sr.destination = "http://www.example.com/Destination"
self.sr.consent = saml.CONSENT_UNSPECIFIED
self.sr.issuer = saml.Issuer()
self.sr.signature = ds.Signature()
self.sr.extensions = samlp.Extensions()
self.sr.status = samlp.Status()
new_sr = samlp.status_response_type_from_string(self.sr.to_string())
assert new_sr.id == "response id"
assert new_sr.in_response_to == "request id"
assert new_sr.version == saml2.VERSION
assert new_sr.issue_instant == "2007-09-14T01:05:02Z"
assert new_sr.destination == "http://www.example.com/Destination"
assert new_sr.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_sr.issuer, saml.Issuer)
assert isinstance(new_sr.signature, ds.Signature)
assert isinstance(new_sr.extensions, samlp.Extensions)
assert isinstance(new_sr.status, samlp.Status)
def testUsingTestData(self):
"""Test for status_response_from_string() using test data"""
# TODO:
pass
class TestResponse:
def setup_class(self):
self.response = samlp.Response()
def testAccessors(self):
"""Test for Response accessors"""
self.response.id = "response id"
self.response.in_response_to = "request id"
self.response.version = saml2.VERSION
self.response.issue_instant = "2007-09-14T01:05:02Z"
self.response.destination = "http://www.example.com/Destination"
self.response.consent = saml.CONSENT_UNSPECIFIED
self.response.issuer = saml.Issuer()
self.response.signature = ds.Signature()
self.response.extensions = samlp.Extensions()
self.response.status = samlp.Status()
self.response.assertion.append(saml.Assertion())
self.response.encrypted_assertion.append(saml.EncryptedAssertion())
new_response = samlp.response_from_string(self.response.to_string())
assert new_response.id == "response id"
assert new_response.in_response_to == "request id"
assert new_response.version == saml2.VERSION
assert new_response.issue_instant == "2007-09-14T01:05:02Z"
assert new_response.destination == "http://www.example.com/Destination"
assert new_response.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_response.issuer, saml.Issuer)
assert isinstance(new_response.signature, ds.Signature)
assert isinstance(new_response.extensions, samlp.Extensions)
assert isinstance(new_response.status, samlp.Status)
assert isinstance(new_response.assertion[0], saml.Assertion)
assert isinstance(new_response.encrypted_assertion[0],
saml.EncryptedAssertion)
def testUsingTestData(self):
"""Test for response_from_string() using test data"""
# TODO:
pass
class TestNameIDPolicy:
def setup_class(self):
self.name_id_policy = samlp.NameIDPolicy()
def testAccessors(self):
"""Test for NameIDPolicy accessors"""
self.name_id_policy.format = saml.NAMEID_FORMAT_EMAILADDRESS
self.name_id_policy.sp_name_qualifier = saml.NAMEID_FORMAT_PERSISTENT
self.name_id_policy.allow_create = 'false'
new_name_id_policy = samlp.name_id_policy_from_string(
self.name_id_policy.to_string())
assert new_name_id_policy.format == saml.NAMEID_FORMAT_EMAILADDRESS
assert new_name_id_policy.sp_name_qualifier == \
saml.NAMEID_FORMAT_PERSISTENT
assert new_name_id_policy.allow_create == 'false'
def testUsingTestData(self):
"""Test for name_id_policy_from_string() using test data"""
new_name_id_policy = samlp.name_id_policy_from_string(
samlp_data.TEST_NAME_ID_POLICY)
assert new_name_id_policy.format == saml.NAMEID_FORMAT_EMAILADDRESS
assert new_name_id_policy.sp_name_qualifier == \
saml.NAMEID_FORMAT_PERSISTENT
assert new_name_id_policy.allow_create == 'false'
class TestIDPEntry:
def setup_class(self):
self.idp_entry = samlp.IDPEntry()
def testAccessors(self):
"""Test for IDPEntry accessors"""
self.idp_entry.provider_id = "http://www.example.com/provider"
self.idp_entry.name = "the provider"
self.idp_entry.loc = "http://www.example.com/Loc"
new_idp_entry = samlp.idp_entry_from_string(self.idp_entry.to_string())
assert new_idp_entry.provider_id == "http://www.example.com/provider"
assert new_idp_entry.name == "the provider"
assert new_idp_entry.loc == "http://www.example.com/Loc"
def testUsingTestData(self):
"""Test for idp_entry_from_string() using test data"""
new_idp_entry = samlp.idp_entry_from_string(samlp_data.TEST_IDP_ENTRY)
assert new_idp_entry.provider_id == "http://www.example.com/provider"
assert new_idp_entry.name == "the provider"
assert new_idp_entry.loc == "http://www.example.com/Loc"
class TestIDPList:
def setup_class(self):
self.idp_list = samlp.IDPList()
def testAccessors(self):
"""Test for IDPList accessors"""
self.idp_list.idp_entry.append(samlp.idp_entry_from_string(
samlp_data.TEST_IDP_ENTRY))
self.idp_list.get_complete = samlp.GetComplete(
text="http://www.example.com/GetComplete")
new_idp_list = samlp.idp_list_from_string(self.idp_list.to_string())
assert isinstance(new_idp_list.idp_entry[0], samlp.IDPEntry)
assert new_idp_list.get_complete.text.strip() == \
"http://www.example.com/GetComplete"
def testUsingTestData(self):
"""Test for idp_list_from_string() using test data"""
new_idp_list = samlp.idp_list_from_string(samlp_data.TEST_IDP_LIST)
assert isinstance(new_idp_list.idp_entry[0], samlp.IDPEntry)
assert new_idp_list.get_complete.text.strip() == \
"http://www.example.com/GetComplete"
class TestScoping:
def setup_class(self):
self.scoping = samlp.Scoping()
def testAccessors(self):
"""Test for Scoping accessors"""
self.scoping.proxy_count = "1"
self.scoping.idp_list = samlp.IDPList()
self.scoping.requester_id.append(samlp.RequesterID())
new_scoping = samlp.scoping_from_string(self.scoping.to_string())
assert new_scoping.proxy_count == "1"
assert isinstance(new_scoping.idp_list, samlp.IDPList)
assert isinstance(new_scoping.requester_id[0], samlp.RequesterID)
def testUsingTestData(self):
"""Test for scoping_from_string() using test data"""
new_scoping = samlp.scoping_from_string(samlp_data.TEST_SCOPING)
assert new_scoping.proxy_count == "1"
assert isinstance(new_scoping.idp_list, samlp.IDPList)
assert isinstance(new_scoping.requester_id[0], samlp.RequesterID)
class TestRequestedAuthnContext:
def setup_class(self):
self.context = samlp.RequestedAuthnContext()
def testAccessors(self):
"""Test for RequestedAuthnContext accessors"""
self.context.authn_context_class_ref.append(saml.AuthnContextClassRef())
self.context.authn_context_decl_ref.append(saml.AuthnContextDeclRef())
self.context.comparison = "exact"
new_context = samlp.requested_authn_context_from_string(
self.context.to_string())
assert isinstance(new_context.authn_context_class_ref[0],
saml.AuthnContextClassRef)
assert isinstance(new_context.authn_context_decl_ref[0],
saml.AuthnContextDeclRef)
assert new_context.comparison == "exact"
def testUsingTestData(self):
"""Test for requested_authn_context_from_string() using test data"""
new_context = samlp.requested_authn_context_from_string(
samlp_data.TEST_REQUESTED_AUTHN_CONTEXT)
assert isinstance(new_context.authn_context_class_ref[0],
saml.AuthnContextClassRef)
assert isinstance(new_context.authn_context_decl_ref[0],
saml.AuthnContextDeclRef)
assert new_context.comparison == "exact"
class TestAuthnRequest:
def setup_class(self):
self.ar = samlp.AuthnRequest()
def testAccessors(self):
"""Test for AuthnRequest accessors"""
self.ar.id = "request id"
self.ar.version = saml2.VERSION
self.ar.issue_instant = "2007-09-14T01:05:02Z"
self.ar.destination = "http://www.example.com/Destination"
self.ar.consent = saml.CONSENT_UNSPECIFIED
self.ar.issuer = saml.Issuer()
self.ar.signature = ds.Signature()
self.ar.extensions = samlp.Extensions()
self.ar.subject = saml.Subject()
self.ar.name_id_policy = samlp.NameIDPolicy()
self.ar.conditions = saml.Conditions()
self.ar.requested_authn_context = samlp.RequestedAuthnContext()
self.ar.scoping = samlp.Scoping()
self.ar.force_authn = 'true'
self.ar.is_passive = 'true'
self.ar.assertion_consumer_service_index = "1"
self.ar.assertion_consumer_service_url = "http://www.example.com/acs"
self.ar.protocol_binding = saml2.BINDING_HTTP_POST
self.ar.attribute_consuming_service_index = "2"
self.ar.provider_name = "provider name"
new_ar = samlp.authn_request_from_string(self.ar.to_string())
assert new_ar.id == "request id"
assert new_ar.version == saml2.VERSION
assert new_ar.issue_instant == "2007-09-14T01:05:02Z"
assert new_ar.destination == "http://www.example.com/Destination"
assert new_ar.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_ar.issuer, saml.Issuer)
assert isinstance(new_ar.signature, ds.Signature)
assert isinstance(new_ar.extensions, samlp.Extensions)
assert isinstance(new_ar.subject, saml.Subject)
assert isinstance(new_ar.name_id_policy, samlp.NameIDPolicy)
assert isinstance(new_ar.conditions, saml.Conditions)
assert isinstance(new_ar.requested_authn_context,
samlp.RequestedAuthnContext)
assert isinstance(new_ar.scoping, samlp.Scoping)
assert new_ar.force_authn == 'true'
assert new_ar.is_passive == 'true'
assert new_ar.assertion_consumer_service_index == '1'
assert new_ar.assertion_consumer_service_url == \
'http://www.example.com/acs'
assert new_ar.protocol_binding == saml2.BINDING_HTTP_POST
assert new_ar.attribute_consuming_service_index == '2'
assert new_ar.provider_name == "provider name"
def testUsingTestData(self):
"""Test for authn_request_from_string() using test data"""
new_ar = samlp.authn_request_from_string(samlp_data.TEST_AUTHN_REQUEST)
assert new_ar.id == "request id"
assert new_ar.version == saml2.VERSION
assert new_ar.issue_instant == "2007-09-14T01:05:02Z"
assert new_ar.destination == "http://www.example.com/Destination"
assert new_ar.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_ar.issuer, saml.Issuer)
assert isinstance(new_ar.signature, ds.Signature)
assert isinstance(new_ar.extensions, samlp.Extensions)
assert isinstance(new_ar.subject, saml.Subject)
assert isinstance(new_ar.name_id_policy, samlp.NameIDPolicy)
assert isinstance(new_ar.conditions, saml.Conditions)
assert isinstance(new_ar.requested_authn_context,
samlp.RequestedAuthnContext)
assert isinstance(new_ar.scoping, samlp.Scoping)
assert new_ar.force_authn == 'true'
assert new_ar.is_passive == 'true'
assert new_ar.assertion_consumer_service_index == '1'
assert new_ar.assertion_consumer_service_url == \
'http://www.example.com/acs'
assert new_ar.protocol_binding == saml2.BINDING_HTTP_POST
assert new_ar.attribute_consuming_service_index == '2'
assert new_ar.provider_name == "provider name"
class TestLogoutRequest:
def setup_class(self):
self.lr = samlp.LogoutRequest()
def testAccessors(self):
"""Test for LogoutRequest accessors"""
self.lr.id = "request id"
self.lr.version = saml2.VERSION
self.lr.issue_instant = "2007-09-14T01:05:02Z"
self.lr.destination = "http://www.example.com/Destination"
self.lr.consent = saml.CONSENT_UNSPECIFIED
self.lr.issuer = saml.Issuer()
self.lr.signature = ds.Signature()
self.lr.extensions = samlp.Extensions()
self.lr.not_on_or_after = "2007-10-14T01:05:02Z"
self.lr.reason = "http://www.example.com/Reason"
self.lr.base_id = saml.BaseID()
self.lr.name_id = saml.NameID()
self.lr.encrypted_id = saml.EncryptedID()
self.lr.session_index = samlp.SessionIndex()
new_lr = samlp.logout_request_from_string(self.lr.to_string())
assert new_lr.id == "request id"
assert new_lr.version == saml2.VERSION
assert new_lr.issue_instant == "2007-09-14T01:05:02Z"
assert new_lr.destination == "http://www.example.com/Destination"
assert new_lr.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_lr.issuer, saml.Issuer)
assert isinstance(new_lr.signature, ds.Signature)
assert isinstance(new_lr.extensions, samlp.Extensions)
assert new_lr.not_on_or_after == "2007-10-14T01:05:02Z"
assert new_lr.reason == "http://www.example.com/Reason"
assert isinstance(new_lr.base_id, saml.BaseID)
assert isinstance(new_lr.name_id, saml.NameID)
assert isinstance(new_lr.encrypted_id, saml.EncryptedID)
assert isinstance(new_lr.session_index[0], samlp.SessionIndex)
def testUsingTestData(self):
"""Test for logout_request_from_string() using test data"""
new_lr = samlp.logout_request_from_string(samlp_data.TEST_LOGOUT_REQUEST)
assert new_lr.id == "request id"
assert new_lr.version == saml2.VERSION
assert new_lr.issue_instant == "2007-09-14T01:05:02Z"
assert new_lr.destination == "http://www.example.com/Destination"
assert new_lr.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_lr.issuer, saml.Issuer)
assert isinstance(new_lr.signature, ds.Signature)
assert isinstance(new_lr.extensions, samlp.Extensions)
assert new_lr.not_on_or_after == "2007-10-14T01:05:02Z"
assert new_lr.reason == "http://www.example.com/Reason"
assert isinstance(new_lr.base_id, saml.BaseID)
assert isinstance(new_lr.name_id, saml.NameID)
assert isinstance(new_lr.encrypted_id, saml.EncryptedID)
assert isinstance(new_lr.session_index[0], samlp.SessionIndex)
assert new_lr.session_index[0].text.strip() == "session index"
class TestLogoutResponse:
def setup_class(self):
self.lr = samlp.LogoutResponse()
def testAccessors(self):
"""Test for LogoutResponse accessors"""
self.lr.id = "response id"
self.lr.in_response_to = "request id"
self.lr.version = saml2.VERSION
self.lr.issue_instant = "2007-09-14T01:05:02Z"
self.lr.destination = "http://www.example.com/Destination"
self.lr.consent = saml.CONSENT_UNSPECIFIED
self.lr.issuer = saml.Issuer()
self.lr.signature = ds.Signature()
self.lr.extensions = samlp.Extensions()
self.lr.status = samlp.Status()
new_lr = samlp.logout_response_from_string(self.lr.to_string())
assert new_lr.id == "response id"
assert new_lr.in_response_to == "request id"
assert new_lr.version == saml2.VERSION
assert new_lr.issue_instant == "2007-09-14T01:05:02Z"
assert new_lr.destination == "http://www.example.com/Destination"
assert new_lr.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_lr.issuer, saml.Issuer)
assert isinstance(new_lr.signature, ds.Signature)
assert isinstance(new_lr.extensions, samlp.Extensions)
assert isinstance(new_lr.status, samlp.Status)
def testUsingTestData(self):
"""Test for logout_response_from_string() using test data"""
new_lr = samlp.logout_response_from_string(
samlp_data.TEST_LOGOUT_RESPONSE)
assert new_lr.id == "response id"
assert new_lr.in_response_to == "request id"
assert new_lr.version == saml2.VERSION
assert new_lr.issue_instant == "2007-09-14T01:05:02Z"
assert new_lr.destination == "http://www.example.com/Destination"
assert new_lr.consent == saml.CONSENT_UNSPECIFIED
assert isinstance(new_lr.issuer, saml.Issuer)
assert isinstance(new_lr.signature, ds.Signature)
assert isinstance(new_lr.extensions, samlp.Extensions)
assert isinstance(new_lr.status, samlp.Status)

1143
tests/test_05_md.py Normal file

File diff suppressed because it is too large Load Diff

444
tests/test_12_s_utils.py Normal file
View File

@@ -0,0 +1,444 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import zlib
import base64
import gzip
from saml2 import make_instance
from saml2 import s_utils as utils
from saml2 import saml
from saml2 import samlp
from saml2 import md
from saml2.s_utils import do_attribute_statement
from saml2.sigver import make_temp
from saml2.saml import Attribute, NAME_FORMAT_URI, AttributeValue
from py.test import raises
SUCCESS_STATUS = """<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<ns0:Status xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol"><ns0:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" /></ns0:Status>"""
ERROR_STATUS = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:Status xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol"><ns0:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder"><ns0:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal" /></ns0:StatusCode><ns0:StatusMessage>Error resolving principal</ns0:StatusMessage></ns0:Status>"""
def _eq(l1,l2):
return set(l1) == set(l2)
def _oeq(l1,l2):
if len(l1) != len(l2):
print "Different number of items"
return False
for item in l1:
if item not in l2:
print "%s not in l2" % (item,)
for ite in l2:
print "\t%s" % (ite,)
return False
return True
def test_inflate_then_deflate():
str = """Selma Lagerlöf (1858-1940) was born in Östra Emterwik, Värmland,
Sweden. She was brought up on Mårbacka, the family estate, which she did
not leave until 1881, when she went to a teachers' college at Stockholm"""
interm = utils.deflate_and_base64_encode(str)
bis = utils.decode_base64_and_inflate(interm)
assert bis == str
def test_status_success():
status = utils.success_status_factory()
status_text = "%s" % status
assert status_text == SUCCESS_STATUS
assert status.status_code.value == samlp.STATUS_SUCCESS
def test_error_status():
status = utils.status_message_factory("Error resolving principal",
samlp.STATUS_UNKNOWN_PRINCIPAL,
samlp.STATUS_RESPONDER)
status_text = "%s" % status
print status_text
assert status_text == ERROR_STATUS
def test_status_from_exception():
e = utils.UnknownPrincipal("Error resolving principal")
stat = utils.status_from_exception_factory(e)
status_text = "%s" % stat
print status_text
assert status_text == ERROR_STATUS
def test_attribute_sn():
attr = utils.do_attributes({"surName":("Jeter", "")})
assert len(attr) == 1
print attr
inst = attr[0]
assert inst.name == "surName"
assert len(inst.attribute_value) == 1
av = inst.attribute_value[0]
assert av.text == "Jeter"
def test_attribute_age():
attr = utils.do_attributes({"age":(37, "")})
assert len(attr) == 1
inst = attr[0]
print inst
assert inst.name == "age"
assert len(inst.attribute_value) == 1
av = inst.attribute_value[0]
assert av.text == "37"
assert av.get_type() == "xs:integer"
def test_attribute_onoff():
attr = utils.do_attributes({"onoff":(False, "")})
assert len(attr) == 1
inst = attr[0]
print inst
assert inst.name == "onoff"
assert len(inst.attribute_value) == 1
av = inst.attribute_value[0]
assert av.text == "false"
assert av.get_type() == "xs:boolean"
def test_attribute_base64():
b64sl = base64.b64encode("Selma Lagerlöf")
attr = utils.do_attributes({"name":(b64sl, "xs:base64Binary")})
assert len(attr) == 1
inst = attr[0]
print inst
assert inst.name == "name"
assert len(inst.attribute_value) == 1
av = inst.attribute_value[0]
assert av.get_type() == "xs:base64Binary"
assert av.text.strip() == b64sl
def test_attribute_statement():
statement = do_attribute_statement({"surName":("Jeter", ""),
"givenName":("Derek", "")})
print statement
assert statement.keyswv() == ["attribute"]
assert len(statement.attribute) == 2
attr0 = statement.attribute[0]
assert _eq(attr0.keyswv(), ["name","attribute_value"])
assert len(attr0.attribute_value) == 1
attr1 = statement.attribute[1]
assert _eq(attr1.keyswv(), ["name","attribute_value"])
assert len(attr1.attribute_value) == 1
if attr0.name == "givenName":
assert attr0.attribute_value[0].text == "Derek"
assert attr1.name == "surName"
assert attr1.attribute_value[0].text == "Jeter"
else:
assert attr0.name == "surName"
assert attr0.attribute_value[0].text == "Jeter"
assert attr1.name == "givenName"
assert attr1.attribute_value[0].text == "Derek"
def test_audience():
aud_restr = utils.factory(saml.AudienceRestriction,
audience=utils.factory(saml.Audience,text="urn:foo:bar"))
assert aud_restr.keyswv() == ["audience"]
assert aud_restr.audience.text == "urn:foo:bar"
def test_conditions():
conditions = utils.factory( saml.Conditions,
not_before="2009-10-30T07:58:10.852Z",
not_on_or_after="2009-10-30T08:03:10.852Z",
audience_restriction=[utils.factory(saml.AudienceRestriction,
audience=utils.factory(saml.Audience,
text="urn:foo:bar"))])
assert _eq(conditions.keyswv(), ["not_before", "not_on_or_after",
"audience_restriction"])
assert conditions.not_before == "2009-10-30T07:58:10.852Z"
assert conditions.not_on_or_after == "2009-10-30T08:03:10.852Z"
assert conditions.audience_restriction[0].audience.text == "urn:foo:bar"
def test_value_1():
#FriendlyName="givenName" Name="urn:oid:2.5.4.42"
# NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
attribute = utils.factory(saml.Attribute, name="urn:oid:2.5.4.42",
name_format=NAME_FORMAT_URI)
assert _eq(attribute.keyswv(),["name","name_format"])
assert attribute.name == "urn:oid:2.5.4.42"
assert attribute.name_format == saml.NAME_FORMAT_URI
def test_value_2():
attribute = utils.factory(saml.Attribute, name="urn:oid:2.5.4.42",
name_format=NAME_FORMAT_URI,
friendly_name="givenName")
assert _eq(attribute.keyswv(),["name","name_format","friendly_name"])
assert attribute.name == "urn:oid:2.5.4.42"
assert attribute.name_format == NAME_FORMAT_URI
assert attribute.friendly_name == "givenName"
def test_value_3():
attribute = utils.factory(saml.Attribute,
attribute_value=[utils.factory(
saml.AttributeValue, text="Derek")],
name="urn:oid:2.5.4.42",
name_format=NAME_FORMAT_URI,
friendly_name="givenName")
assert _eq(attribute.keyswv(),["name", "name_format",
"friendly_name", "attribute_value"])
assert attribute.name == "urn:oid:2.5.4.42"
assert attribute.name_format == NAME_FORMAT_URI
assert attribute.friendly_name == "givenName"
assert len(attribute.attribute_value) == 1
assert attribute.attribute_value[0].text == "Derek"
def test_value_4():
attribute = utils.factory(saml.Attribute,
attribute_value=[utils.factory(
saml.AttributeValue, text="Derek")],
friendly_name="givenName")
assert _eq(attribute.keyswv(),["friendly_name", "attribute_value"])
assert attribute.friendly_name == "givenName"
assert len(attribute.attribute_value) == 1
assert attribute.attribute_value[0].text == "Derek"
def test_do_attribute_statement_0():
statement = do_attribute_statement({"vo_attr":("foobar", "")})
assert statement.keyswv() == ["attribute"]
assert len(statement.attribute) == 1
attr0 = statement.attribute[0]
assert _eq(attr0.keyswv(), ["name","attribute_value"])
assert attr0.name == "vo_attr"
assert len(attr0.attribute_value) == 1
assert attr0.attribute_value[0].text == "foobar"
def test_do_attribute_statement():
statement = do_attribute_statement({"surName":("Jeter", ""),
"givenName":(["Derek",
"Sanderson"], "")})
assert statement.keyswv() == ["attribute"]
assert len(statement.attribute) == 2
attr0 = statement.attribute[0]
assert _eq(attr0.keyswv(), ["name","attribute_value"])
attr1 = statement.attribute[1]
assert _eq(attr1.keyswv(), ["name","attribute_value"])
if attr0.name == "givenName":
assert len(attr0.attribute_value) == 2
assert _eq([av.text for av in attr0.attribute_value],
["Derek","Sanderson"])
assert attr1.name == "surName"
assert attr1.attribute_value[0].text == "Jeter"
assert len(attr1.attribute_value) == 1
else:
assert attr0.name == "surName"
assert attr0.attribute_value[0].text == "Jeter"
assert len(attr0.attribute_value) == 1
assert attr1.name == "givenName"
assert len(attr1.attribute_value) == 2
assert _eq([av.text for av in attr1.attribute_value],
["Derek","Sanderson"])
def test_do_attribute_statement_multi():
statement = do_attribute_statement(
{( "urn:oid:1.3.6.1.4.1.5923.1.1.1.7",
"urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
"eduPersonEntitlement"):("Jeter", "")})
assert statement.keyswv() == ["attribute"]
assert len(statement.attribute)
assert _eq(statement.attribute[0].keyswv(),
["name","name_format","friendly_name","attribute_value"])
attribute = statement.attribute[0]
assert attribute.name == "urn:oid:1.3.6.1.4.1.5923.1.1.1.7"
assert attribute.name_format == (
"urn:oasis:names:tc:SAML:2.0:attrname-format:uri")
assert attribute.friendly_name == "eduPersonEntitlement"
def test_subject():
subject = utils.factory(saml.Subject, text="_aaa",
name_id=saml.NameID(
text=saml.NAMEID_FORMAT_TRANSIENT))
assert _eq(subject.keyswv(),["text", "name_id"])
assert subject.text == "_aaa"
assert subject.name_id.text == saml.NAMEID_FORMAT_TRANSIENT
# ---------------------------------------------------------------------------
def test_parse_attribute_map():
(forward, backward) = utils.parse_attribute_map(["attribute.map"])
assert _eq(forward.keys(), backward.values())
assert _eq(forward.values(), backward.keys())
print forward.keys()
assert _oeq(forward.keys(), [
('urn:oid:1.3.6.1.4.1.5923.1.1.1.7', NAME_FORMAT_URI),
('urn:oid:0.9.2342.19200300.100.1.1', NAME_FORMAT_URI),
('urn:oid:1.3.6.1.4.1.5923.1.1.1.1', NAME_FORMAT_URI),
('urn:oid:2.5.4.42', NAME_FORMAT_URI),
('urn:oid:2.5.4.4', NAME_FORMAT_URI),
('urn:oid:0.9.2342.19200300.100.1.3', NAME_FORMAT_URI),
('urn:oid:2.5.4.12', NAME_FORMAT_URI)])
assert _eq(forward.keys(), [
('urn:oid:1.3.6.1.4.1.5923.1.1.1.7', NAME_FORMAT_URI),
('urn:oid:0.9.2342.19200300.100.1.1', NAME_FORMAT_URI),
('urn:oid:1.3.6.1.4.1.5923.1.1.1.1', NAME_FORMAT_URI),
('urn:oid:2.5.4.42', NAME_FORMAT_URI),
('urn:oid:2.5.4.4', NAME_FORMAT_URI),
('urn:oid:0.9.2342.19200300.100.1.3', NAME_FORMAT_URI),
('urn:oid:2.5.4.12', NAME_FORMAT_URI)])
assert _eq(backward.keys(),["surName","givenName","title","uid","mail",
"eduPersonAffiliation",
"eduPersonEntitlement"])
def test_identity_attribute_0():
(forward, backward) = utils.parse_attribute_map(["attribute.map"])
a = Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI,
friendly_name="surName")
assert utils.identity_attribute("name",a,forward) == "urn:oid:2.5.4.4"
assert utils.identity_attribute("friendly",a,forward) == "surName"
def test_identity_attribute_1():
(forward, backward) = utils.parse_attribute_map(["attribute.map"])
a = Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI)
assert utils.identity_attribute("name",a,forward) == "urn:oid:2.5.4.4"
assert utils.identity_attribute("friendly",a,forward) == "surName"
def test_identity_attribute_2():
(forward, backward) = utils.parse_attribute_map(["attribute.map"])
a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI)
assert utils.identity_attribute("name",a,forward) == "urn:oid:2.5.4.5"
# if there would be a map it would be serialNumber
assert utils.identity_attribute("friendly",a,forward) == "urn:oid:2.5.4.5"
def test_identity_attribute_3():
a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI)
assert utils.identity_attribute("name",a) == "urn:oid:2.5.4.5"
# if there would be a map it would be serialNumber
assert utils.identity_attribute("friendly",a) == "urn:oid:2.5.4.5"
def test_identity_attribute_4():
a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
friendly_name="serialNumber")
assert utils.identity_attribute("name",a) == "urn:oid:2.5.4.5"
# if there would be a map it would be serialNumber
assert utils.identity_attribute("friendly",a) == "serialNumber"
def _givenName(a):
assert a["name"] == "urn:oid:2.5.4.42"
assert a["friendly_name"] == "givenName"
assert len(a["attribute_value"]) == 1
assert a["attribute_value"] == [{"text":"Derek"}]
def _surName(a):
assert a["name"] == "urn:oid:2.5.4.4"
assert a["friendly_name"] == "surName"
assert len(a["attribute_value"]) == 1
assert a["attribute_value"] == [{"text":"Jeter"}]
def test_nameformat_email():
assert utils.valid_email("foo@example.com")
assert utils.valid_email("a@b.com")
assert utils.valid_email("a@b.se")
assert utils.valid_email("john@doe@johndoe.com") == False
def test_attribute():
a = utils.factory(saml.Attribute,
friendly_name="eduPersonScopedAffiliation",
name="urn:oid:1.3.6.1.4.1.5923.1.1.1.9",
name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")
assert _eq(a.keyswv(), ["friendly_name","name", "name_format"])
a = utils.factory(saml.Attribute,
friendly_name="eduPersonScopedAffiliation",
name="urn:oid:1.3.6.1.4.1.5923.1.1.1.9",
name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
attribute_value=[saml.AttributeValue(text="member@example.com")])
assert _eq(a.keyswv(), ["friendly_name","name", "name_format",
"attribute_value"])
def test_attribute_statement():
statement = utils.factory( saml.Statement,
attribute=[
utils.factory(saml.Attribute,
attribute_value=[
utils.factory(
saml.AttributeValue,text="Derek")],
friendly_name="givenName"),
utils.factory(saml.Attribute,
attribute_value=[
utils.factory(
saml.AttributeValue,text="Jeter")],
friendly_name="surName"),
])
assert statement.keyswv() == ["attribute"]
assert len(statement.attribute) == 2
def test_subject_confirmation_data():
s = utils.factory( saml.SubjectConfirmation,
in_response_to="_12345678",
not_before="2010-02-11T07:30:00Z",
not_on_or_after="2010-02-11T07:35:00Z",
recipient="http://example.com/sp/",
address="192.168.0.10")
assert _eq(s.keyswv(),["in_response_to","not_before","not_on_or_after",
"recipient", "address"])
def test_subject_confirmation():
s = utils.factory( saml.SubjectConfirmation,
method="urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser",
base_id="1234",
name_id="abcd",
subject_confirmation_data=utils.factory(
saml.SubjectConfirmationData,
in_response_to="_1234567890",
recipient="http://example.com/sp/"))
assert _eq(s.keyswv(),
["method","base_id","name_id","subject_confirmation_data"])
assert s.method == "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser"
def test_authn_context_class_ref():
a = utils.factory( saml.AuthnContextClassRef,
text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")
assert a.keyswv() == ["text"]
assert a.text == "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"
def test_authn_context():
accr = utils.factory( saml.AuthnContext,
text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")
a = utils.factory(saml.AuthnContext, authn_context_class_ref=accr)
assert a.keyswv() == ["authn_context_class_ref"]
def test_authn_statement():
accr = utils.factory( saml.AuthnContextClassRef,
text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")
ac = utils.factory( saml.AuthnContext,
authn_context_class_ref=accr)
ast = utils.factory( saml.AuthnStatement,
authn_instant="2010-03-10T12:33:00Z",
session_index="_12345",
session_not_on_or_after="2010-03-11T12:00:00Z",
authn_context=ac
)
assert _eq(ast.keyswv(),["authn_instant","session_index",
"session_not_on_or_after",
"authn_context"])

61
tests/test_43_soap.py Executable file
View File

@@ -0,0 +1,61 @@
#!/usr/bin/env python
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
from elementtree import ElementTree
import saml2.samlp as samlp
from saml2.samlp import NAMESPACE as SAMLP_NAMESPACE
NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/"
example = """<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_6c3a4f8b9c2d" Version="2.0" IssueInstant="2004-03-27T08:42:00Z">
<saml:Issuer>https://www.example.com/SAML</saml:Issuer>
<Status>
<StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/>
</Status>
<saml:Assertion>
<saml:Subject></saml:Subject>
<saml:AttributeStatement></saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>
</Body>
</Envelope>
"""
def test_parse_soap_envelope():
envelope = ElementTree.fromstring(example)
assert envelope.tag == '{%s}Envelope' % NAMESPACE
# How to check that it's the right type ?
assert len(envelope) == 1
body = envelope[0]
assert body.tag == '{%s}Body' % NAMESPACE
assert len(body) == 1
saml_part = body[0]
assert saml_part.tag == '{%s}Response' % SAMLP_NAMESPACE
# {http://schemas.xmlsoap.org/soap/envelope/}Envelope
def test_make_soap_envelope():
envelope = ElementTree.Element('')
envelope.tag = '{%s}Envelope' % NAMESPACE
body = ElementTree.Element('')
body.tag = '{%s}Body' % NAMESPACE
envelope.append(body)
request = samlp.AuthnRequest()
request.become_child_element_of(body)
string = ElementTree.tostring(envelope, encoding="UTF-8")
result = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/"><ns0:Body><ns1:AuthnRequest xmlns:ns1="urn:oasis:names:tc:SAML:2.0:protocol" /></ns0:Body></ns0:Envelope>"""
assert string == result