From 046204bf6b7c0bf3e39a6dd8c527cc18c51061bd Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Wed, 21 Jul 2010 13:04:15 +0200 Subject: [PATCH] Numerous changes more than can be stated here. Basically all the modules made by hand from the SAML XML schemas has been replaced with modules made by a XML Schema -> Python module script. This change has caused a lot of necessary changes in code that depends on the format/content of the SAML modules. The configuration has changed, partly because the need to support more than one endpoint. --- src/s2repoze/plugins/sp.py | 78 +- src/saml2/__init__.py | 43 +- src/saml2/assertion.py | 52 +- src/saml2/attribute_converter.py | 35 +- src/saml2/attribute_resolver.py | 3 +- src/saml2/authnresponse.py | 31 +- src/saml2/cache.py | 19 +- src/saml2/client.py | 276 ++- src/saml2/config.py | 38 +- src/saml2/md.py | 2840 +++++++++++++------------- src/saml2/metadata.py | 37 +- src/saml2/saml.py | 2117 +++++++++---------- src/saml2/samlp.py | 2506 +++++++++++++---------- src/saml2/server.py | 59 +- src/saml2/sigver.py | 166 +- src/saml2/soap.py | 9 +- src/saml2/utils.py | 11 + src/xmldsig/__init__.py | 2328 ++++++++++++--------- src/xmlenc/__init__.py | 1073 +++++----- tests/ds_data.py | 2 +- tests/idp.config | 7 +- tests/md_data.py | 45 +- tests/restrictive_idp.config | 8 +- tests/samlp_data.py | 2 +- tests/server.config | 20 +- tests/test_00_saml2.py | 541 ----- tests/test_01_saml.py | 989 --------- tests/test_02_md.py | 1166 ----------- tests/test_03_samlp.py | 535 ----- tests/test_11_utils.py | 443 ---- tests/test_20_assertion.py | 11 +- tests/test_21_attribute_converter.py | 60 +- tests/test_30_metadata.py | 44 +- tests/test_31_config.py | 37 +- tests/test_33_identifier.py | 36 +- tests/test_40_sigver.py | 247 +-- tests/test_41_xmldsig.py | 655 ------ tests/test_42_xmlenc.py | 175 -- tests/test_44_authnresp.py | 11 +- tests/test_50_server.py | 98 +- tests/test_51_client.py | 150 +- tools/make_metadata.py | 373 ++-- 42 files changed, 6986 insertions(+), 10390 deletions(-) delete mode 100644 tests/test_00_saml2.py delete mode 100644 tests/test_01_saml.py delete mode 100644 tests/test_02_md.py delete mode 100644 tests/test_03_samlp.py delete mode 100644 tests/test_11_utils.py delete mode 100644 tests/test_41_xmldsig.py delete mode 100644 tests/test_42_xmlenc.py diff --git a/src/s2repoze/plugins/sp.py b/src/s2repoze/plugins/sp.py index 1f8266c..dac264c 100644 --- a/src/s2repoze/plugins/sp.py +++ b/src/s2repoze/plugins/sp.py @@ -36,7 +36,7 @@ from repoze.who.plugins.form import FormPluginBase from saml2.client import Saml2Client from saml2.attribute_resolver import AttributeResolver from saml2.config import Config -from saml2.cache import Cache +from saml2.population import Population def construct_came_from(environ): """ The URL that the user used when the process where interupted @@ -55,7 +55,12 @@ def cgi_fieldStorage_to_dict( fieldStorage ): params = {} for key in fieldStorage.keys(): - params[ key ] = fieldStorage[ key ].value + try: + params[ key ] = fieldStorage[ key ].value + except AttributeError: + if isinstance(fieldStorage[ key ], basestring): + params[key] = fieldStorage[key] + return params class SAML2Plugin(FormPluginBase): @@ -92,19 +97,8 @@ class SAML2Plugin(FormPluginBase): self.outstanding_queries = {} self.iam = os.uname()[1] - if cache: - self.cache = Cache(cache) - else: - self.cache = Cache() - - def _cache_session(self, session_info): - name_id = session_info["name_id"] - issuer = session_info["issuer"] - del session_info["issuer"] - self.cache.set(name_id, issuer, session_info, - session_info["not_on_or_after"]) - return name_id - + self.users = Population(cache) + def _pick_idp(self, environ): """ If more than one idp and if none is selected, I have to do wayf or @@ -234,7 +228,7 @@ class SAML2Plugin(FormPluginBase): session_info = ar.session_info() # Cache it - name_id = self._cache_session(session_info) + name_id = self.users.add_information_about_person(session_info) if self.debug: self.log and self.log.info("stored %s with key %s" % ( session_info, name_id)) @@ -299,56 +293,6 @@ class SAML2Plugin(FormPluginBase): else: return None - def _vo_members_to_ask(self, subject_id): - # Find the member of the Virtual Organization that I haven't - # alrady spoken too - vo_members = [ - member for member in self.metadata.vo_members(self.vorg)\ - if member not in self.srv["idp"].keys()] - - self.log and self.log.info("VO members: %s" % vo_members) - - # Remove the ones I have cached data from about this subject - vo_members = [m for m in vo_members \ - if not self.cache.active(subject_id, m)] - self.log and self.log.info( - "VO members (not cached): %s" % vo_members) - return vo_members - - def _do_vo_aggregation(self, subject_id): - - if self.log: - self.log.info("** Do VO aggregation **") - self.log.info("SubjectID: %s, VO:%s" % (subject_id, self.vorg)) - - vo_members = self._vo_members_to_ask(subject_id) - - if vo_members: - # Find the NameIDFormat and the SPNameQualifier - if self.vorg_conf and "name_id_format" in self.vorg_conf: - name_id_format = self.vorg_conf["name_id_format"] - sp_name_qualifier = "" - else: - sp_name_qualifier = self.vorg - name_id_format = "" - - resolver = AttributeResolver(environ, self.metadata, self.conf) - # extends returns a list of session_infos - for session_info in resolver.extend(subject_id, - self.conf["entityid"], vo_members, - name_id_format=name_id_format, - sp_name_qualifier=sp_name_qualifier, - log=self.log): - _ignore = self._cache_session(session_info) - - self.log.info( - ">Issuers: %s" % self.cache.entities(subject_id)) - self.log.info( - "AVA: %s" % (self.cache.get_identity(subject_id),)) - - return True - else: - return False # IMetadataProvider def add_metadata(self, environ, identity): @@ -381,7 +325,7 @@ class SAML2Plugin(FormPluginBase): if "pysaml2_vo_expanded" not in identity: # is this a Virtual Organization situation if self.vorg: - if self._do_vo_aggregation(subject_id): + if self.vorg.do_vo_aggregation(subject_id): # Get the extended identity identity["user"] = self.cache.get_identity(subject_id)[0] # Only do this once, mark that the identity has been diff --git a/src/saml2/__init__.py b/src/saml2/__init__.py index d6fedaa..4d05855 100644 --- a/src/saml2/__init__.py +++ b/src/saml2/__init__.py @@ -31,6 +31,22 @@ provides methods and functions to convert SAML classes to and from strings. """ +# try: +# # lxml: best performance for XML processing +# import lxml.etree as ET +# except ImportError: +# try: +# # Python 2.5+: batteries included +# import xml.etree.cElementTree as ET +# except ImportError: +# try: +# # Python <2.5: standalone ElementTree install +# import elementtree.cElementTree as ET +# except ImportError: +# raise ImportError, "lxml or ElementTree are not installed, "\ +# +"see http://codespeak.net/lxml "\ +# +"or http://effbot.org/zone/element-index.htm" + try: from xml.etree import cElementTree as ElementTree except ImportError: @@ -45,7 +61,7 @@ NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' NAMEID_FORMAT_EMAILADDRESS = ( "urn:oasis:names:tc:SAML:2.0:nameid-format:emailAddress") -URN_PASSWORD = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password" + NAME_FORMAT_UNSPECIFIED = ( "urn:oasis:names:tc:SAML:2.0:attrnam-format:unspecified") NAME_FORMAT_URI = "urn:oasis:names:tc:SAML:2.0:attrnam-format:uri" @@ -83,10 +99,10 @@ def create_class_from_xml_string(target_class, xml_string): not match those of the target class. """ tree = ElementTree.fromstring(xml_string) - return _create_class_from_element_tree(target_class, tree) + return create_class_from_element_tree(target_class, tree) -def _create_class_from_element_tree(target_class, tree, namespace=None, +def create_class_from_element_tree(target_class, tree, namespace=None, tag=None): """Instantiates the class and populates members according to the tree. @@ -411,6 +427,9 @@ class SamlBase(ExtensionContainer): c_children = {} c_attributes = {} + c_attribute_type = {} + #c_attribute_use = {} + c_attribute_required = {} c_child_order = [] def _get_all_c_children_with_order(self): @@ -433,11 +452,11 @@ class SamlBase(ExtensionContainer): if getattr(self, member_name) is None: setattr(self, member_name, []) getattr(self, member_name).append( - _create_class_from_element_tree( + create_class_from_element_tree( member_class[0], child_tree)) else: setattr(self, member_name, - _create_class_from_element_tree(member_class, + create_class_from_element_tree(member_class, child_tree)) else: ExtensionContainer._convert_element_tree_to_member(self, @@ -449,7 +468,7 @@ class SamlBase(ExtensionContainer): # Find the member of this class which corresponds to the XML # attribute(lookup in current_class.c_attributes) and set this # member to the desired value (using self.__dict__). - setattr(self, self.__class__.c_attributes[attribute], value) + setattr(self, self.__class__.c_attributes[attribute][0], value) else: # If it doesn't appear in the attribute list it's an extension ExtensionContainer._convert_element_attribute_to_member(self, @@ -470,8 +489,9 @@ class SamlBase(ExtensionContainer): else: member.become_child_element_of(tree) # Convert the members of this class which are XML attributes. - for xml_attribute, member_name in \ + for xml_attribute, attribute_info in \ self.__class__.c_attributes.iteritems(): + (member_name, member_type, required) = attribute_info member = getattr(self, member_name) if member is not None: tree.attrib[xml_attribute] = member @@ -514,7 +534,8 @@ class SamlBase(ExtensionContainer): def _init_attribute(self, extension_attribute_id, extension_attribute_name, value=None): - self.c_attributes[extension_attribute_id] = extension_attribute_name + self.c_attributes[extension_attribute_id] = (extension_attribute_name, + None, False) if value: self.__dict__[extension_attribute_name] = value @@ -532,7 +553,7 @@ class SamlBase(ExtensionContainer): :return: list of keys """ keys = ['text'] - keys.extend(self.c_attributes.values()) + keys.extend([n for (n, t, r) in self.c_attributes.values()]) keys.extend([v[1] for v in self.c_children.values()]) return keys @@ -592,7 +613,7 @@ class SamlBase(ExtensionContainer): :return: The instance """ - for prop in self.c_attributes.values(): + for prop, _typ, _req in self.c_attributes.values(): #print "# %s" % (prop) if prop in ava: if isinstance(ava[prop], bool): @@ -641,7 +662,7 @@ def element_to_extension_element(element): exel = ExtensionElement(element.c_tag, element.c_namespace, text=element.text) - for xml_attribute, member_name in element.c_attributes.iteritems(): + for xml_attribute, (member_name, typ, req) in element.c_attributes.iteritems(): member_value = getattr(element, member_name) if member_value is not None: exel.attributes[xml_attribute] = member_value diff --git a/src/saml2/assertion.py b/src/saml2/assertion.py index 75d5923..68fef04 100644 --- a/src/saml2/assertion.py +++ b/src/saml2/assertion.py @@ -23,12 +23,14 @@ from saml2 import saml from saml2.time_util import instant, in_a_while from saml2.attribute_converter import from_local -from saml2.utils import sid, MissingValue -from saml2.utils import args2dict -from saml2.utils import assertion_factory +from saml2.s_utils import sid, MissingValue +from saml2.s_utils import factory +from saml2.s_utils import assertion_factory +from saml2.s_utils import do_attribute_statement def _filter_values(vals, required=None, optional=None): - """ Removes values from *val* that does not appear in *attributes*. + """ Removes values from *vals* that does not appear in *required* + or *optional*. :param val: The values that are to be filtered :param required: The required values @@ -314,12 +316,13 @@ class Policy(object): return self.filter(ava, sp_entity_id, required, optional) def conditions(self, sp_entity_id): - return args2dict( + return factory( saml.Conditions, not_before=instant(), # How long might depend on who's getting it not_on_or_after=self._not_on_or_after(sp_entity_id), - audience_restriction=args2dict( - audience=args2dict(sp_entity_id))) + audience_restriction=[factory( saml.AudienceRestriction, + audience=factory(saml.Audience, + text=sp_entity_id))]) class Assertion(dict): """ Handles assertions about subjects """ @@ -327,14 +330,28 @@ class Assertion(dict): def __init__(self, dic=None): dict.__init__(self, dic) - def _authn_statement(self): - return args2dict(authn_instant=instant(), session_index=sid()) + def _authn_context(self, authn_class): + return factory(saml.AuthnContext, + authn_context_class_ref=factory( + saml.AuthnContextClassRef, text=authn_class)) + + def _authn_statement(self, authn_class): + if authn_class: + return factory(saml.AuthnStatement, + authn_instant=instant(), + session_index=sid(), + authn_context=self._authn_context(authn_class)) + else: + return factory(saml.AuthnStatement, + authn_instant=instant(), + session_index=sid()) def construct(self, sp_entity_id, in_response_to, name_id, attrconvs, - policy, issuer): + policy, issuer, authn_class=None): - attr_statement = from_local(attrconvs, self, - policy.get_name_form(sp_entity_id)) + attr_statement = saml.AttributeStatement(attribute=from_local( + attrconvs, self, + policy.get_name_form(sp_entity_id))) # start using now and for a hour conds = policy.conditions(sp_entity_id) @@ -342,14 +359,15 @@ class Assertion(dict): return assertion_factory( issuer=issuer, attribute_statement = attr_statement, - authn_statement = self._authn_statement(), + authn_statement = self._authn_statement(authn_class), conditions = conds, - subject=args2dict( + subject=factory( saml.Subject, name_id=name_id, method=saml.SUBJECT_CONFIRMATION_METHOD_BEARER, - subject_confirmation=args2dict( - subject_confirmation_data = \ - args2dict(in_response_to=in_response_to))), + subject_confirmation=factory( saml.SubjectConfirmation, + subject_confirmation_data=factory( + saml.SubjectConfirmationData, + in_response_to=in_response_to))), ) def apply_policy(self, sp_entity_id, policy, metadata=None): diff --git a/src/saml2/attribute_converter.py b/src/saml2/attribute_converter.py index 418e872..5d76fe8 100644 --- a/src/saml2/attribute_converter.py +++ b/src/saml2/attribute_converter.py @@ -16,7 +16,8 @@ # limitations under the License. import os -from saml2.utils import args2dict +from saml2.s_utils import factory, do_ava +from saml2 import saml from saml2.saml import NAME_FORMAT_URI class UnknownNameFormat(Exception): @@ -64,7 +65,7 @@ def from_local(acs, ava, name_format): #print ac.format, name_format if aconv.name_format == name_format: #print "Found a name_form converter" - return aconv.to(ava) + return aconv.to_(ava) return None @@ -73,7 +74,7 @@ def from_local_name(acs, attr, name_format): :param acs: List of AttributeConverter instances :param attr: attribute name as string :param name_format: Which name-format it should be translated to - :return: A dictionary suitable to feed to make_instance + :return: An Attribute instance """ for aconv in acs: #print ac.format, name_format @@ -118,7 +119,7 @@ class AttributeConverter(object): self._to = eval(open(filename).read()) def adjust(self): - if self._fro == None and self.to != None: + if self._fro == None and self._to != None: self._fro = dict([(value, key) for key, value in self._to.items()]) if self._to == None and self.fro != None: self._to = dict([(value, key) for key, value in self._fro.items()]) @@ -184,10 +185,12 @@ class AttributeConverter(object): def to_format(self, attr): try: - return args2dict(name=self._to[attr], name_format=self.name_format, - friendly_name=attr) + return factory(saml.Attribute, + name=self._to[attr], + name_format=self.name_format, + friendly_name=attr) except KeyError: - return args2dict(name=attr) + return factory(saml.Attribute, name=attr) def from_format(self, attr): """ @@ -201,18 +204,18 @@ class AttributeConverter(object): pass return "" - def to(self, ava): + def to_(self, attrvals): attributes = [] - for key, value in ava.items(): + for key, value in attrvals.items(): try: - attributes.append(args2dict(name=self._to[key], + attributes.append(factory(saml.Attribute, + name=self._to[key], name_format=self.name_format, friendly_name=key, - attribute_value=value)) + attribute_value=do_ava(value))) except KeyError: - # TODO - # Should this be made different ??? - attributes.append(args2dict(name=key, - attribute_value=value)) + attributes.append(factory(saml.Attribute, + name=key, + attribute_value=do_ava(value))) - return {"attribute": attributes} \ No newline at end of file + return attributes \ No newline at end of file diff --git a/src/saml2/attribute_resolver.py b/src/saml2/attribute_resolver.py index 51cf68b..cd26197 100644 --- a/src/saml2/attribute_resolver.py +++ b/src/saml2/attribute_resolver.py @@ -20,7 +20,6 @@ Contains classes and functions that a SAML2.0 Service Provider (SP) may use to do attribute aggregation. """ import saml2 -from saml2.client import Saml2Client DEFAULT_BINDING = saml2.BINDING_HTTP_REDIRECT @@ -32,7 +31,7 @@ class AttributeResolver(object): if saml2client: self.saml2client = saml2client else: - self.saml2client = Saml2Client(environ, config) + self.saml2client = saml2.client.Saml2Client(environ, config) def extend(self, subject_id, issuer, vo_members, name_id_format=None, sp_name_qualifier=None, log=None): diff --git a/src/saml2/authnresponse.py b/src/saml2/authnresponse.py index 42555b9..05ea819 100644 --- a/src/saml2/authnresponse.py +++ b/src/saml2/authnresponse.py @@ -31,6 +31,11 @@ from saml2.time_util import daylight_corrected_now # --------------------------------------------------------------------------- +class IncorrectlySigned(Exception): + pass + +# --------------------------------------------------------------------------- + def _use_on_or_after(condition, slack): now = daylight_corrected_now() #print "NOW: %d" % now @@ -57,23 +62,17 @@ def _use_before(condition, slack): return True def for_me(condition, myself ): + # Am I among the intended audiences for restriction in condition.audience_restriction: - audience = restriction.audience - if audience.text.strip() == myself: - return True - else: - #print "Not for me: %s != %s" % (audience.text.strip(), myself) - pass + for audience in restriction.audience: + if audience.text.strip() == myself: + return True + else: + #print "Not for me: %s != %s" % (audience.text.strip(), myself) + pass return False -# --------------------------------------------------------------------------- - -class IncorrectlySigned(Exception): - pass - -# --------------------------------------------------------------------------- - def authn_response(conf, requestor, outstanding_queries=None, log=None, timeslack=0, debug=0): sec = security_context(conf) @@ -128,7 +127,6 @@ class AuthnResponse(object): self.response = self.sec.correctly_signed_response(decoded_xml) except Exception, excp: self.log and self.log.info("EXCEPTION: %s", excp) - raise if not self.response: if self.log: @@ -180,7 +178,7 @@ class AuthnResponse(object): self.not_on_or_after = _use_on_or_after(condition, self.timeslack) _use_before(condition, self.timeslack) except Exception, excp: - self.log.error("Exception on condition: %s" % (excp,)) + self.log and self.log.error("Exception on condition: %s" % (excp,)) if not lax: raise else: @@ -230,6 +228,7 @@ class AuthnResponse(object): # The subject must contain a name_id assert subject.name_id self.name_id = subject.name_id.text.strip() + return self.name_id def _assertion(self, assertion): self.assertion = assertion @@ -294,7 +293,7 @@ class AuthnResponse(object): return True def verify(self): - """ Verify that the assertion is syntaktically correct and + """ Verify that the assertion is syntactically correct and the signature is correct if present.""" self.status_ok() diff --git a/src/saml2/cache.py b/src/saml2/cache.py index f32527f..b463734 100644 --- a/src/saml2/cache.py +++ b/src/saml2/cache.py @@ -2,6 +2,7 @@ import shelve import time +from saml2 import time_util # The assumption is that any subject may consist of data # gathered from several different sources, all with their own @@ -19,6 +20,9 @@ class Cache(object): self._db = {} self._sync = False + def delete(self, subject_id): + del self._db[subject_id] + def get_identity(self, subject_id, entities=None): """ Get all the identity information that has been received and are still valid about the subject. @@ -53,24 +57,27 @@ class Cache(object): return (res, oldees) def get(self, subject_id, entity_id): - """ Get seesion information about a the session when an - assertion was received from an IdP or an AA or sent to a SP. + """ Get session information about a subject gotten from a + specified IdP. :param subject_id: The identifier of the subject :param entity_id: The identifier of the entity_id :return: The session information """ (not_on_or_after, info) = self._db[subject_id][entity_id] - now = time.gmtime() + if isinstance(not_on_or_after, time.struct_time): + not_on_or_after = time.mktime(not_on_or_after) + now = time_util.daylight_corrected_now() if not_on_or_after < now: - self.reset(subject_id, entity_id) - raise ToOld() + #self.reset(subject_id, entity_id) + raise ToOld("%s < %s" % (not_on_or_after, now)) else: return info def set( self, subject_id, entity_id, info, not_on_or_after=0): - """ Stores session information in the cache + """ Stores session information in the cache. Assumes that the subject_id + is unique within the context of the Service Provider. :param subject_id: The subjects identifier :param entity_id: The identifier of the entity_id/receiver of an diff --git a/src/saml2/client.py b/src/saml2/client.py index d943aba..d4f0361 100644 --- a/src/saml2/client.py +++ b/src/saml2/client.py @@ -25,14 +25,16 @@ import saml2 import base64 from saml2.time_util import instant -from saml2.utils import sid, deflate_and_base64_encode -from saml2.utils import do_attributes, args2dict +from saml2.s_utils import sid, deflate_and_base64_encode +from saml2.s_utils import do_attributes, factory -from saml2 import samlp, saml -from saml2 import VERSION, make_instance +from saml2 import samlp, saml, class_name +from saml2 import VERSION from saml2.sigver import pre_signature_part from saml2.sigver import security_context, signed_instance_factory from saml2.soap import SOAPClient +from saml2.population import Population +from saml2.virtual_org import VirtualOrg from saml2.authnresponse import authn_response @@ -46,19 +48,32 @@ FORM_SPEC = """
LAX = False +class IdpUnspecified(Exception): + pass + +class VerifyError(Exception): + pass + class Saml2Client(object): """ The basic pySAML2 service provider class """ - def __init__(self, environ, config=None, debug=0): + def __init__(self, environ, config=None, debug=0, vorg=None, + persistent_cache=None): """ :param environ: :param config: A saml2.config.Config instance """ self.environ = environ + self.vorg = None + self.users = Population(persistent_cache) if config: self.config = config if "metadata" in config: self.metadata = config["metadata"] + if vorg: + self.vorg = VirtualOrg(self.metadata, vorg, + self.users.cache, + log=None, vorg_conf=None) self.sec = security_context(config) self.debug = debug @@ -71,32 +86,23 @@ class Saml2Client(object): return request def idp_entry(self, name=None, location=None, provider_id=None): - res = {} + res = samlp.IDPEntry() if name: - res["name"] = name + res.name = name if location: - res["loc"] = location + res.loc = location if provider_id: - res["provider_id"] = provider_id - if res: - return res - else: - return None + res.provider_id = provider_id + + return res - def scoping(self, idp_ents): - return { - "idp_list": { - "idp_entry": idp_ents - } - } - - def scoping_from_metadata(self, entityid, location): + def scoping_from_metadata(self, entityid, location=None): name = self.metadata.name(entityid) - return make_instance(samlp.Scoping, - self.scoping([self.idp_entry(name, location)])) + idp_ent = self.idp_entry(name, location) + return samlp.Scoping(idp_list=samlp.IDPList(idp_entry=[idp_ent])) def response(self, post, requestor, outstanding, log=None): - """ Deal with the AuthnResponse + """ Deal with an AuthnResponse :param post: The reply as a dictionary :param requestor: The issuer of the AuthN request @@ -104,10 +110,8 @@ class Saml2Client(object): the original web request from the user before redirection as values. :param log: where loggin should go. - :return: A 2-tuple of identity information (in the form of a - dictionary) and where the user should really be sent. This - might differ from what the IdP thinks since I don't want - to reveal verything to it and it might not trust me. + :return: An authnresponse.AuthnResponse instance which among other + things contains a verified saml2.AuthnResponse instance. """ # If the request contains a samlResponse, try to validate it try: @@ -115,15 +119,18 @@ class Saml2Client(object): except KeyError: return None + aresp = None if saml_response: aresp = authn_response(self.config, requestor, outstanding, log, debug=self.debug) aresp.loads(saml_response) if self.debug: log and log.info(aresp) - return aresp.verify() - - return None + aresp = aresp.verify() + if aresp: + self.users.add_information_about_person(aresp.session_info()) + + return aresp def authn_request(self, query_id, destination, service_url, spentityid, my_name, vorg="", scoping=None, log=None, sign=False): @@ -139,45 +146,78 @@ class Saml2Client(object): :param log: A service to which logs should be written :param sign: Whether the request should be signed or not. """ - prel = { - "id": query_id, - "version": VERSION, - "issue_instant": instant(), - "destination": destination, - "assertion_consumer_service_url": service_url, - "protocol_binding": saml2.BINDING_HTTP_POST, - "provider_name": my_name, - } + request = samlp.AuthnRequest( + id= query_id, + version= VERSION, + issue_instant= instant(), + destination= destination, + assertion_consumer_service_url= service_url, + protocol_binding= saml2.BINDING_HTTP_POST, + provider_name= my_name + ) if scoping: - prel["scoping"] = scoping + request.scoping = scoping - name_id_policy = { - "allow_create": "true" - } + # Profile stuff, should be configurable + name_id_policy = samlp.NameIDPolicy(allow_create="true", + format=saml.NAMEID_FORMAT_TRANSIENT) - name_id_policy["format"] = saml.NAMEID_FORMAT_TRANSIENT if vorg: try: - name_id_policy["sp_name_qualifier"] = vorg - name_id_policy["format"] = saml.NAMEID_FORMAT_PERSISTENT + name_id_policy.sp_name_qualifier = vorg + name_id_policy.format = saml.NAMEID_FORMAT_PERSISTENT except KeyError: pass if sign: - prel["signature"] = pre_signature_part(prel["id"], - self.sec.my_cert, id=1) + request.signature = pre_signature_part(request.id, + self.sec.my_cert, 1) + to_sign = [(class_name(request), request.id)] + else: + to_sign = [] - prel["name_id_policy"] = name_id_policy - prel["issuer"] = { "text": spentityid } + request.name_id_policy = name_id_policy + request.issuer = factory(saml.Issuer, text=spentityid ) if log: - log.info("DICT VERSION: %s" % prel) + log.info("REQUEST: %s" % request) - return "%s" % signed_instance_factory(samlp.AuthnRequest, prel, - self.sec) + return "%s" % signed_instance_factory(request, self.sec, to_sign) - def authenticate(self, spentityid, location="", service_url="", + def issuer(self): + """ Return an Issuer instance """ + return saml.Issuer(text=self.config["entityid"], + format=saml.NAMEID_FORMAT_ENTITY) + + def _spentityid(self, spentityid=None): + if self.config: + return self.config["entityid"] + else: + return spentityid + + def _location(self, location=None): + if not location : + # get the idp location from the configuration alternative the metadata + # If there is more than one IdP in the configuration raise exception + urls = self.config.idps() + if len(urls) > 1: + raise IdpUnspecified("Too many IdPs to choose from: %s" % urls) + return urls[0] + else: + return location + + def _service_url(self, url=None): + if not url: + return self.config.endpoint("sp", "assertion_consumer_service")[0] + + def _my_name(self, name=None): + if not name: + return self.config["service"]["sp"]["name"] + else: + return name + + def authenticate(self, spentityid=None, location="", service_url="", my_name="", relay_state="", binding=saml2.BINDING_HTTP_REDIRECT, log=None, vorg="", scoping=None): @@ -199,11 +239,17 @@ class Saml2Client(object): :return: AuthnRequest response """ + spentityid = self._spentityid(spentityid) + location = self._location(location) + service_url = self._service_url(service_url) + my_name = self._my_name(my_name) + if log: log.info("spentityid: %s" % spentityid) log.info("location: %s" % location) log.info("service_url: %s" % service_url) log.info("my_name: %s" % my_name) + session_id = sid() authen_req = self.authn_request(session_id, location, service_url, spentityid, my_name, vorg, @@ -229,7 +275,8 @@ class Saml2Client(object): lista = ["SAMLRequest=%s" % urllib.quote_plus( deflate_and_base64_encode( authen_req)), - "spentityid=%s" % spentityid] + #"spentityid=%s" % spentityid + ] if relay_state: lista.append("RelayState=%s" % relay_state) login_url = "?".join([location, "&".join(lista)]) @@ -263,35 +310,35 @@ class Saml2Client(object): """ - subject = args2dict( - name_id = args2dict(subject_id, format=nameid_format, + subject = saml.Subject( + name_id = saml.NameID( + text=subject_id, + format=nameid_format, sp_name_qualifier=sp_name_qualifier, name_qualifier=name_qualifier), ) - prequery = { - "id": session_id, - "version": VERSION, - "issue_instant": instant(), - "destination": destination, - "issuer": issuer, - "subject":subject, - } + query = samlp.AttributeQuery( + id=session_id, + version=VERSION, + issue_instant=instant(), + destination=destination, + issuer=self.issuer(), + subject=subject, + ) if sign: - prequery["signature"] = pre_signature_part(prequery["id"], - self.sec.my_cert, 1) + query.signature = pre_signature_part(query.id, self.sec.my_cert, 1) if attribute: - prequery["attribute"] = do_attributes(attribute) + query.attribute = do_attributes(attribute) - request = make_instance(samlp.AttributeQuery, prequery) if sign: - signed_req = self.sec.sign_assertion_using_xmlsec("%s" % request) - return samlp.attribute_query_from_string(signed_req) + signed_query = self.sec.sign_assertion_using_xmlsec("%s" % query) + return samlp.attribute_query_from_string(signed_query) else: - return request + return query def attribute_query(self, subject_id, issuer, destination, @@ -333,6 +380,9 @@ class Saml2Client(object): aresp = authn_response(self.config, issuer, {session_id:""}, log) session_info = aresp.loads(response).verify().session_info() + + if session_info: + self.users.add_information_about_person(session_info) log and log.info("session: %s" % session_info) return session_info @@ -340,8 +390,8 @@ class Saml2Client(object): log and log.info("No response") return None - def make_logout_request(self, session_id, destination, issuer, - reason=None, not_on_or_after=None): + def make_logout_requests(self, subject_id, reason=None, + not_on_or_after=None): """ Constructs a LogoutRequest :param subject_id: The identifier of the subject @@ -349,32 +399,68 @@ class Saml2Client(object): form of a URI reference. :param not_on_or_after: The time at which the request expires, after which the recipient may discard the message. - :return: An AttributeQuery instance + :return: A LogoutRequest instance """ + + result = [] + + for entity_id in self.users.issuers_of_info(subject_id): + destination = self.config["service"]["sp"]["idp"][entity_id] + + # create NameID from subject_id + name_id = NameID( + text=self.client.users.get_entityid(subject_id, + entity_id)["name_id"]) + + request = samlp.LogoutRequest( + id=sid(), + version=VERSION, + issue_instant=instant(), + destination=destination, + issuer=self.issuer(), + session_index=session_id, + name_id = name_id + ) + - prel = { - "id": sid(), - "version": VERSION, - "issue_instant": instant(), - "destination": destination, - "issuer": issuer, - "session_index": session_id, - } + if reason: + request.reason = reason - if reason: - prel["reason"] = reason - - if not_on_or_after: - prel["not_on_or_after"] = not_on_or_after - - return make_instance(samlp.LogoutRequest, prel) + if not_on_or_after: + request.not_on_or_after = not_on_or_after + + result.append(request) + + return result - def logout(self, session_id, destination, - issuer, reason="", not_on_or_after=None): - return self.make_logout_request(session_id, destination, - issuer, reason, not_on_or_after) + def global_logout(self, subject_id, reason="", not_on_or_after=None): + requests = self.make_logout_requests(subject_id, reason, + not_on_or_after) + return [r.id for r in requests] + + def local_logout(self, subject_id, reason="", not_on_or_after=None): + # Remove the user from the cache, equals local logout + self.users.remove_person(subject_id) + return True + def add_vo_information_about_user(self, subject_id): + """ Add information to the knowledge I have about the user """ + try: + (ava, _) = self.users.get_identity(subject_id) + except KeyError: + pass + + # is this a Virtual Organization situation + if self.vorg: + if self.vorg.do_vo_aggregation(subject_id): + # Get the extended identity + ava = self.users.get_identity(subject_id)[0] + return ava + + def is_session_valid(session_id): + return True + # ---------------------------------------------------------------------- ROW = """%s%s""" diff --git a/src/saml2/config.py b/src/saml2/config.py index a1a5972..baad48d 100644 --- a/src/saml2/config.py +++ b/src/saml2/config.py @@ -43,11 +43,11 @@ class Config(dict): assert "idp" in config assert len(config["idp"]) > 0 - assert "url" in config + assert "endpoints" in config assert "name" in config def _idp_aa_check(self, config): - assert "url" in config + assert "endpoints" in config if "assertions" in config: config["policy"] = Policy(config["assertions"]) del config["assertions"] @@ -95,7 +95,8 @@ class Config(dict): config["metadata"] = self.load_metadata(config["metadata"], config["xmlsec_binary"], config["attrconverters"]) - + self.metadata = config["metadata"] + if "sp" in config["service"]: #print config["service"]["sp"] if "metadata" in config: @@ -130,15 +131,36 @@ class Config(dict): except KeyError: return Policy() - def aa_url(self): - return self["service"]["aa"]["url"] + def endpoint(self, typ, service): + try: + return self["service"][typ]["endpoints"][service] + except KeyError: + return None - def idp_url(self): - return self["service"]["idp"]["url"] - def vo_conf(self, name): return self["virtual_organization"][name] def attribute_converters(self): return self["attrconverters"] + + def idps(self): + """ Returns a list of URLs of the IdP this SP can + use according to the configuration""" + + try: + return [u for u in self["service"]["sp"]["idp"].values()] + except KeyError: + return [] + def is_wayf_needed(self): + if len(self["service"]["sp"]["idp"]) > 1: + return True + else: # not really true, what if it's zero (0) + return False + + def get_available_idps(self): + lista = [] + for eid, url in self["service"]["sp"]["idp"].items(): + namn = self.metadata.name(eid) + lista.append((eid, namn)) + return lista \ No newline at end of file diff --git a/src/saml2/md.py b/src/saml2/md.py index 8bce907..ab79e2e 100644 --- a/src/saml2/md.py +++ b/src/saml2/md.py @@ -1,1704 +1,1620 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright (C) 2007 SIOS Technology, Inc. -# 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. +#!/usr/bin/env python -"""Contains classes representing Metadata elements. +# +# Generated Sat Jul 17 11:11:48 2010 by parse_xsd.py version 0.3. +# - Module objective: provide data classes for Metadata - constructs. These classes hide the XML-ness of Saml and provide a - set of native Python classes to interact with. +import saml2 +from saml2 import SamlBase -""" - -from saml2 import saml, SamlBase, create_class_from_xml_string -from saml2.saml import Attribute -from saml2.saml import NAMESPACE as SAML_NAMESPACE +from saml2 import saml import xmldsig as ds -from xmldsig import NAMESPACE as DS_NAMESPACE -from xmlenc import NAMESPACE as XMLENC_NAMESPACE +import xmlenc as xenc NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:metadata' -#MD_TEMPLATE = '{urn:oasis:names:tc:SAML:2.0:metadata}%s' -XML_TEMPLATE = '{http:#www.w3.org/XML/1998/namespace}%s' -DESCRIPTOR_CHOICE = ["role_descriptor", "idp_sso_descriptor", - "sp_sso_descriptor", -# "authn_authority_descriptor", - "attribute_authority_descriptor", - "pdp_descriptor" - ] - -CONTACT_TYPES = ["technical", "support", "administrative", "billing", "other"] +class entityIDType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:entityIDType element """ -def correct(element): - """ Checks whether an element instance adhers to the standard - - :param element: The element instance - :return: Boolean True if it is according to the standard specification - otherwise False. - """ - - if hasattr(element, "c_required_attributes"): - for attr in element.c_required_attributes: - if getattr(element, attr) == None: - return False - - # go through the children - for child in element.children_with_values(): - if correct(child) == False: - return False - - if isinstance(element, EntitiesDescriptor): - # The has to be at least one - if len(element.entity_descriptor) == 0 and \ - len(element.entities_descriptor) == 0: - return False - elif isinstance(element, EntityDescriptor): - if len(element.affiliation_descriptor) > 1: - return False - elif len(element.affiliation_descriptor) == 1: - for descriptor in DESCRIPTOR_CHOICE: - if getattr(element, descriptor) != []: - return False - return True - else: - for descriptor in DESCRIPTOR_CHOICE: - if getattr(element, descriptor) != []: - return True - return False - elif isinstance(element, Organization): - for prop in ["organizational_name", "organizational_display_name", - "organization_url"]: - if getattr(element, prop) == []: - return False - elif isinstance(element, ContactPerson): - for child in ["company", "givenname", "surname"]: - if len(getattr(element, child)) > 1: - return False - if element.contact_type not in CONTACT_TYPES: - return False - elif isinstance(element, RoleDescriptor): - for child in ["signature", "extensions", "organization"]: - if len(getattr(element, child)) > 1: - return False - elif isinstance(element, KeyDescriptor): - if element.key_info == []: - return False - elif isinstance(element, IDPSSODescriptor): - if element.single_sign_on_service == []: - return False - elif isinstance(element, SPSSODescriptor): - if element.assertion_consumer_service == []: - return False - elif isinstance(element, AttributeConsumingService): - if element.service_name == []: - return False - if element.requested_attribute == []: - return False -# elif isinstance(element, AuthnAuthorityDescriptor): -# if element.authn_query_service == []: -# return False - elif isinstance(element, PDPDescriptor): - if element.authz_service == []: - return False - elif isinstance(element, AttributeAuthorityDescriptor): - if element.attribute_service == []: - return False - elif isinstance(element, AffiliationDescriptor): - if element.affiliate_member == []: - return False - if len(element.signature) > 1: - return False - if len(element.extensions) > 1: - return False - return True - -class Extensions(SamlBase): - """The md:Extensions element""" + c_tag = 'entityIDType' + c_namespace = NAMESPACE + c_value_type = {'maxlen': '1024', 'base': 'anyURI'} + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - c_tag = 'Extensions' +def entity_id_type_from_string(xml_string): + return saml2.create_class_from_xml_string(entityIDType, xml_string) + +class localizedNameType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:localizedNameType element """ + + c_tag = 'localizedNameType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['{http://www.w3.org/XML/1998/namespace}lang'] = ('lang', '', True) -def extensions_from_string(xml_string): - """ Create Extensions instance from an XML string """ - return create_class_from_xml_string(Extensions, xml_string) + def __init__(self, + lang=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.lang=lang -class LocalizedName(SamlBase): - """The md:LocalizedName abstract type""" - c_tag = 'LocalizedName' +def localized_name_type_from_string(xml_string): + return saml2.create_class_from_xml_string(localizedNameType, xml_string) + +class localizedURIType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:localizedURIType element """ + + c_tag = 'localizedURIType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes[XML_TEMPLATE % 'lang'] = 'lang' - c_required_attributes = ["lang"] + c_child_order = SamlBase.c_child_order[:] + c_attributes['{http://www.w3.org/XML/1998/namespace}lang'] = ('lang', '', True) - def __init__(self, lang=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for LocalizedName + def __init__(self, + lang=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.lang=lang - :param lang: xml:lang attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +def localized_uri_type_from_string(xml_string): + return saml2.create_class_from_xml_string(localizedURIType, xml_string) - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.lang = lang +class ExtensionsType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:ExtensionsType element """ -def localized_name_from_string(xml_string): - """ Create LocalizedName instance from an XML string """ - return create_class_from_xml_string(LocalizedName, xml_string) - -class LocalizedURI(SamlBase): - """The md:LocalizedURI abstract type""" - c_tag = 'LocalizedURI' + c_tag = 'ExtensionsType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes[XML_TEMPLATE % 'lang'] = 'lang' - c_required_attributes = ["lang"] - - def __init__(self, lang=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for LocalizedURI + c_child_order = SamlBase.c_child_order[:] - :param lang: xml:lang attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +def extensions_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ExtensionsType, xml_string) - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.lang = lang +class EndpointType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:EndpointType element """ -def localized_uri_from_string(xml_string): - """ Create LocalizedURI instance from an XML string """ - return create_class_from_xml_string(LocalizedURI, xml_string) + c_tag = 'EndpointType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['Binding'] = ('binding', 'anyURI', True) + c_attributes['Location'] = ('location', 'anyURI', True) + c_attributes['ResponseLocation'] = ('response_location', 'anyURI', False) + def __init__(self, + binding=None, + location=None, + response_location=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.binding=binding + self.location=location + self.response_location=response_location + +def endpoint_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EndpointType, xml_string) + +class IndexedEndpointType(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:IndexedEndpointType element """ + + c_tag = 'IndexedEndpointType' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] + c_attributes['index'] = ('index', 'unsignedShort', True) + c_attributes['isDefault'] = ('is_default', 'boolean', False) + + def __init__(self, + index=None, + is_default=None, + binding=None, + location=None, + response_location=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + EndpointType.__init__(self, + binding=binding, + location=location, + response_location=response_location, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.index=index + self.is_default=is_default + +def indexed_endpoint_type_from_string(xml_string): + return saml2.create_class_from_xml_string(IndexedEndpointType, xml_string) + +class OrganizationName(localizedNameType): + """The urn:oasis:names:tc:SAML:2.0:metadata:OrganizationName element """ -class OrganizationName(LocalizedName): - """The md:OrganizationName element""" c_tag = 'OrganizationName' c_namespace = NAMESPACE - c_children = LocalizedName.c_children.copy() - c_attributes = LocalizedName.c_attributes.copy() - - def __init__(self, lang=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for OrganizationName - - :param lang: xml:lang attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - LocalizedName.__init__(self, lang, text, extension_elements, - extension_attributes) - + c_children = localizedNameType.c_children.copy() + c_attributes = localizedNameType.c_attributes.copy() + c_child_order = localizedNameType.c_child_order[:] def organization_name_from_string(xml_string): - """ Create OrganizationName instance from an XML string """ - return create_class_from_xml_string(OrganizationName, xml_string) + return saml2.create_class_from_xml_string(OrganizationName, xml_string) +class OrganizationDisplayName(localizedNameType): + """The urn:oasis:names:tc:SAML:2.0:metadata:OrganizationDisplayName element """ -class OrganizationDisplayName(LocalizedName): - """The md:OrganizationDisplayName element""" c_tag = 'OrganizationDisplayName' c_namespace = NAMESPACE - c_children = LocalizedName.c_children.copy() - c_attributes = LocalizedName.c_attributes.copy() - - def __init__(self, lang=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for OrganizationDisplayName - - :param lang: xml:lang attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - LocalizedName.__init__(self, lang, text, extension_elements, - extension_attributes) - + c_children = localizedNameType.c_children.copy() + c_attributes = localizedNameType.c_attributes.copy() + c_child_order = localizedNameType.c_child_order[:] def organization_display_name_from_string(xml_string): - """ Create OrganizationDisplayName instance from an XML string """ - return create_class_from_xml_string(OrganizationDisplayName, xml_string) + return saml2.create_class_from_xml_string(OrganizationDisplayName, xml_string) +class OrganizationURL(localizedURIType): + """The urn:oasis:names:tc:SAML:2.0:metadata:OrganizationURL element """ -class OrganizationURL(LocalizedURI): - """The md:OrganizationURL element""" c_tag = 'OrganizationURL' c_namespace = NAMESPACE - c_children = LocalizedURI.c_children.copy() - c_attributes = LocalizedURI.c_attributes.copy() - - def __init__(self, lang=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for OrganizationURL - - :param lang: xml:lang attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - LocalizedURI.__init__(self, lang, text, extension_elements, - extension_attributes) + c_children = localizedURIType.c_children.copy() + c_attributes = localizedURIType.c_attributes.copy() + c_child_order = localizedURIType.c_child_order[:] def organization_url_from_string(xml_string): - """ Create OrganizationURL instance from an XML string """ - return create_class_from_xml_string(OrganizationURL, xml_string) + return saml2.create_class_from_xml_string(OrganizationURL, xml_string) - -class Organization(SamlBase): - """The md:Organization base type""" - - c_tag = 'Organization' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_children['{%s}Extensions' % NAMESPACE] = ('extensions', Extensions) - c_children['{%s}OrganizationName' % NAMESPACE] = ( - 'organization_name', [OrganizationName]) - c_children['{%s}OrganizationDisplayName' % NAMESPACE] = ( - 'organization_display_name', [OrganizationDisplayName]) - c_children['{%s}OrganizationURL' % NAMESPACE] = ( - 'organization_url', [OrganizationURL]) - child_order = ['extensions', 'organization_name', - 'organization_display_name', 'organization_url'] - - def __init__(self, extensions=None, organization_name=None, - organization_display_name=None, organization_url=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for Organization - - :param extensions: Extensions element - :param organization_name: OrganizationName elements - :param organization_display_name: OrganizationDisplayName elements - :param organization_url: OrganizationURL elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.extensions = extensions - self.organization_name = organization_name or [] - self.organization_display_name = organization_display_name or [] - self.organization_url = organization_url or [] - -def organization_from_string(xml_string): - """ Create Organization instance from an XML string """ - return create_class_from_xml_string(Organization, xml_string) - - -class Endpoint(SamlBase): - """The md:Endpoint base type""" - - c_tag = 'Endpoint' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['Binding'] = 'binding' - c_attributes['Location'] = 'location' - c_attributes['ResponseLocation'] = 'response_location' - c_required_attributes = ["binding", "location"] - def __init__(self, binding=None, location=None, response_location=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for Endpoint - - :param binding: Binding attribute - :param location: Location attribute - :param response_location: ResponseLocation attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.binding = binding - self.location = location - self.response_location = response_location - -def endpoint_from_string(xml_string): - """ Create Endpoint instance from an XML string """ - return create_class_from_xml_string(Endpoint, xml_string) - - -# --------------------------------------------------------------------------- - -class IndexedEndpoint(Endpoint): - """The md:IndexedEndpoint base type""" - - c_tag = 'IndexedEndpoint' - c_namespace = NAMESPACE - c_children = Endpoint.c_children.copy() - c_attributes = Endpoint.c_attributes.copy() - c_attributes['index'] = 'index' - c_attributes['isDefault'] = 'is_default' - c_required_attributes = Endpoint.c_required_attributes[:] - c_required_attributes.append("index") - - def __init__(self, index=None, is_default=None, binding=None, - location=None, response_location=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for IndexedEndpoint - - :param index: index attribute - :param is_default: isDefault attribute - :param binding: Binding attribute - :param location: Location attribute - :param response_location: ResponseLocation attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - Endpoint.__init__(self, binding, location, response_location, - text, extension_elements, extension_attributes) - self.index = index - self.is_default = is_default - -def indexed_endpoint_from_string(xml_string): - """ Create IndexedEndpoint instance from an XML string """ - return create_class_from_xml_string(IndexedEndpoint, xml_string) - -# --------------------------------------------------------------------------- - -class AuthzService(Endpoint): - - c_tag = 'AuthzService' - c_namespace = NAMESPACE - c_children = Endpoint.c_children.copy() - c_attributes = Endpoint.c_attributes.copy() - - def __init__(self, binding=None, - location=None, response_location=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for AuthzService - - :param binding: Binding attribute - :param location: Location attribute - :param response_location: ResponseLocation attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - Endpoint.__init__(self, binding, location, response_location, - text, extension_elements, extension_attributes) - -def authz_service_from_string(xml_string): - """ Create AuthzService instance from an XML string """ - return create_class_from_xml_string(AuthzService, xml_string) - -# --------------------------------------------------------------------------- - -class AssertionIDRequestService(Endpoint): - - c_tag = 'AssertionIDRequestService' - c_namespace = NAMESPACE - c_children = Endpoint.c_children.copy() - c_attributes = Endpoint.c_attributes.copy() - -def assertion_id_request_service_from_string(xml_string): - """ Create AssertionIDRequestService instance from an XML string """ - return create_class_from_xml_string(AssertionIDRequestService, xml_string) - -# --------------------------------------------------------------------------- - -class AuthnQueryService(Endpoint): - - c_tag = 'AuthnQueryService' - c_namespace = NAMESPACE - c_children = Endpoint.c_children.copy() - c_attributes = Endpoint.c_attributes.copy() - -def authn_query_service_from_string(xml_string): - """ Create AuthnQueryService instance from an XML string """ - return create_class_from_xml_string(AuthnQueryService, xml_string) - -# --------------------------------------------------------------------------- - class Company(SamlBase): - """The md:Company element""" + """The urn:oasis:names:tc:SAML:2.0:metadata:Company element """ c_tag = 'Company' c_namespace = NAMESPACE + c_value_type = 'string' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def company_from_string(xml_string): - """ Create Company instance from an XML string """ - return create_class_from_xml_string(Company, xml_string) - -# --------------------------------------------------------------------------- + return saml2.create_class_from_xml_string(Company, xml_string) class GivenName(SamlBase): - """The md:GivenName element""" + """The urn:oasis:names:tc:SAML:2.0:metadata:GivenName element """ c_tag = 'GivenName' c_namespace = NAMESPACE + c_value_type = 'string' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def given_name_from_string(xml_string): - """ Create GivenName instance from an XML string """ - return create_class_from_xml_string(GivenName, xml_string) - + return saml2.create_class_from_xml_string(GivenName, xml_string) class SurName(SamlBase): - """The md:SurName element""" + """The urn:oasis:names:tc:SAML:2.0:metadata:SurName element """ c_tag = 'SurName' c_namespace = NAMESPACE + c_value_type = 'string' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def sur_name_from_string(xml_string): - """ Create SurName instance from an XML string """ - return create_class_from_xml_string(SurName, xml_string) - + return saml2.create_class_from_xml_string(SurName, xml_string) class EmailAddress(SamlBase): - """The md:EmailAddress element""" + """The urn:oasis:names:tc:SAML:2.0:metadata:EmailAddress element """ c_tag = 'EmailAddress' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def email_address_from_string(xml_string): - """ Create EmailAddress instance from an XML string """ - return create_class_from_xml_string(EmailAddress, xml_string) - + return saml2.create_class_from_xml_string(EmailAddress, xml_string) class TelephoneNumber(SamlBase): - """The md:TelephoneNumber element""" + """The urn:oasis:names:tc:SAML:2.0:metadata:TelephoneNumber element """ c_tag = 'TelephoneNumber' c_namespace = NAMESPACE + c_value_type = 'string' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def telephone_number_from_string(xml_string): - """ Create TelephoneNumber instance from an XML string """ - return create_class_from_xml_string(TelephoneNumber, xml_string) + return saml2.create_class_from_xml_string(TelephoneNumber, xml_string) +class ContactTypeType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:ContactTypeType element """ -class ContactPerson(SamlBase): - """The md:ContactPerson element""" + c_tag = 'ContactTypeType' + c_namespace = NAMESPACE + c_value_type = {'base': 'string', 'enumeration': ['technical', 'support', 'administrative', 'billing', 'other']} + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - c_tag = 'ContactPerson' +def contact_type_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ContactTypeType, xml_string) + +class AdditionalMetadataLocationType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:AdditionalMetadataLocationType element """ + + c_tag = 'AdditionalMetadataLocationType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['contactType'] = 'contact_type' - c_required_attributes = ["contact_type"] - c_children['{%s}Extensions' % NAMESPACE] = ('extensions', Extensions) - c_children['{%s}Company' % NAMESPACE] = ('company', Company) - c_children['{%s}GivenName' % NAMESPACE] = ('given_name', GivenName) - c_children['{%s}SurName' % NAMESPACE] = ('sur_name', SurName) - c_children['{%s}EmailAddress' % NAMESPACE] = ( - 'email_address', [EmailAddress]) - c_children['{%s}TelephoneNumber' % NAMESPACE] = ( - 'telephone_number', [TelephoneNumber]) - c_child_order = ['extensions', 'company', 'given_name', 'sur_name', - 'email_address', 'telephone_number'] + c_child_order = SamlBase.c_child_order[:] + c_attributes['namespace'] = ('namespace', 'anyURI', True) - def __init__(self, extensions=None, contact_type=None, company=None, - given_name=None, sur_name=None, email_address=None, - telephone_number=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for ContactPerson + def __init__(self, + namespace=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.namespace=namespace - :param extensions: Extensions element - :param contact_type: contactType attribute - :param company: Company element - :param given_name: GivenName element - :param sur_name: SurName element - :param email_address: EmailAddress elements - :param telephone_number: TelephoneNumber elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.contact_type = contact_type - self.extensions = extensions - self.company = company - self.given_name = given_name - self.sur_name = sur_name - self.email_address = email_address or [] - self.telephone_number = telephone_number or [] +def additional_metadata_location_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AdditionalMetadataLocationType, xml_string) -def contact_person_from_string(xml_string): - """ Create ContactPerson instance from an XML string """ - return create_class_from_xml_string(ContactPerson, xml_string) +class anyURIListType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:anyURIListType element """ - -class AdditionalMetadataLocation(SamlBase): - """The md:AdditionalMetadataLocation element""" - - c_tag = 'AdditionalMetadataLocation' + c_tag = 'anyURIListType' c_namespace = NAMESPACE + c_value_type = {'member': 'anyURI', 'base': 'list'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['namespace'] = 'namespace' - c_required_attributes = ["namespace"] - - def __init__(self, namespace=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AdditionalMetadataLocation + c_child_order = SamlBase.c_child_order[:] - :param namespace: namespace attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.namespace = namespace +def any_uri_list_type_from_string(xml_string): + return saml2.create_class_from_xml_string(anyURIListType, xml_string) -def additional_metadata_location_from_string(xml_string): - """ Create AdditionalMetadataLocation instance from an XML string """ - return create_class_from_xml_string(AdditionalMetadataLocation, xml_string) +class KeyTypes(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:KeyTypes element """ - -class KeySize(SamlBase): - """The xmlenc:KeySize element""" - - c_tag = 'KeySize' - c_namespace = XMLENC_NAMESPACE + c_tag = 'KeyTypes' + c_namespace = NAMESPACE + c_value_type = {'base': 'string', 'enumeration': ['encryption', 'signing']} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def key_size_from_string(xml_string): - """ Create KeySize instance from an XML string """ - return create_class_from_xml_string(KeySize, xml_string) +def key_types_from_string(xml_string): + return saml2.create_class_from_xml_string(KeyTypes, xml_string) - -class OAEPparams(SamlBase): - """The xmlenc:OAEPparams element""" - - c_tag = 'OAEPparams' - c_namespace = XMLENC_NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - -def oae_pparams_from_string(xml_string): - """ Create OAEPparams instance from an XML string """ - return create_class_from_xml_string(OAEPparams, xml_string) - - -class EncryptionMethod(SamlBase): - """The md:EncryptionMethod element""" +class EncryptionMethod(xenc.EncryptionMethodType): + """The urn:oasis:names:tc:SAML:2.0:metadata:EncryptionMethod element """ c_tag = 'EncryptionMethod' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['Algorithm'] = 'algorithm' - c_children['{%s}KeySize' % XMLENC_NAMESPACE] = ('key_size', KeySize) - c_children['{%s}OAEPparams' % XMLENC_NAMESPACE] = ( - 'oaep_params', OAEPparams) - c_children['{%s}DigestMethod' % DS_NAMESPACE] = ( - 'digest_method', ds.DigestMethod) - c_child_order = ['key_size', 'oaep_params', 'digest_method'] - - def __init__(self, algorithm=None, key_size=None, digest_method=None, - oaep_params=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for EncryptionMethod - - :param algorithm: Algorithm attribute - :param key_size: KeySize Element - :param digest_method: DigestMethod Element - :param oaep_params: OAEPparams Element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.algorithm = algorithm - self.key_size = key_size - self.digest_method = digest_method - self.oaep_params = oaep_params + c_children = xenc.EncryptionMethodType.c_children.copy() + c_attributes = xenc.EncryptionMethodType.c_attributes.copy() + c_child_order = xenc.EncryptionMethodType.c_child_order[:] def encryption_method_from_string(xml_string): - """ Create EncryptionMethod instance from an XML string """ - return create_class_from_xml_string(EncryptionMethod, xml_string) + return saml2.create_class_from_xml_string(EncryptionMethod, xml_string) +class ArtifactResolutionService(IndexedEndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:ArtifactResolutionService element """ -class KeyDescriptor(SamlBase): - """The md:KeyDescriptor element""" - - c_tag = 'KeyDescriptor' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['use'] = 'use' - c_children['{%s}KeyInfo' % DS_NAMESPACE] = ('key_info', ds.KeyInfo) - c_children['{%s}EncryptionMethod' % NAMESPACE] = ( - 'encryption_method', [EncryptionMethod]) - c_child_order = ['key_info', 'encryption_method'] - c_required_child = ["key_info"] - - def __init__(self, use=None, key_info=None, encryption_method=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for KeyDescriptor - - :param use: use attribute - :param key_info: KeyInfo element - :param encryption_method: EncryptionMethod elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.use = use - self.key_info = key_info - self.encryption_method = encryption_method or [] - -def key_descriptor_from_string(xml_string): - """ Create KeyDescriptor instance from an XML string """ - return create_class_from_xml_string(KeyDescriptor, xml_string) - - -class RoleDescriptor(SamlBase): - """The md:RoleDescriptor element""" - - c_tag = 'RoleDescriptor' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['ID'] = 'id' - c_attributes['validUntil'] = 'valid_until' - c_attributes['cacheDuration'] = 'cache_duration' - c_attributes['protocolSupportEnumeration'] = 'protocol_support_enumeration' - c_attributes['errorURL'] = 'error_url' - c_required_attributes = ["protocol_support_enumeration"] - c_children['{%s}Signature' % DS_NAMESPACE] = ('signature', ds.Signature) - c_children['{%s}Extensions' % NAMESPACE] = ('extensions', Extensions) - c_children['{%s}KeyDescriptor' % NAMESPACE] = ( - 'key_descriptor', [KeyDescriptor]) - c_children['{%s}Organization' % NAMESPACE] = ( - 'organization', Organization) - c_children['{%s}ContactPerson' % NAMESPACE] = ( - 'contact_person', [ContactPerson]) - c_child_order = ['signature', 'extensions', 'key_descriptor', - 'organization', 'contact_person'] - - def __init__(self, id=None, valid_until=None, cache_duration=None, - protocol_support_enumeration=None, error_url=None, - signature=None, extensions=None, key_descriptor=None, - organization=None, contact_person=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for RoleDescriptor - - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param protocol_support_enumeration: protocolSupportEnumeration attribute - :param error_url: errorURL attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param key_descriptor: KeyDescriptor elements - :param organization: Organization element - :param contact_person: ContactPerson elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.id = id - self.valid_until = valid_until - self.cache_duration = cache_duration - self.protocol_support_enumeration = protocol_support_enumeration - self.error_url = error_url - self.signature = signature - self.extensions = extensions - self.key_descriptor = key_descriptor or [] - self.organization = organization - self.contact_person = contact_person or [] - -def role_descriptor_from_string(xml_string): - """ Create RoleDescriptor instance from an XML string """ - return create_class_from_xml_string(RoleDescriptor, xml_string) - -# ---------------------------------------------------------------------------- - - -class ArtifactResolutionService(IndexedEndpoint): - """The md:ArtifactResolutionService element""" c_tag = 'ArtifactResolutionService' + c_namespace = NAMESPACE + c_children = IndexedEndpointType.c_children.copy() + c_attributes = IndexedEndpointType.c_attributes.copy() + c_child_order = IndexedEndpointType.c_child_order[:] def artifact_resolution_service_from_string(xml_string): - """ Create ArtifactResolutionService instance from an XML string """ - return create_class_from_xml_string(ArtifactResolutionService, xml_string) + return saml2.create_class_from_xml_string(ArtifactResolutionService, xml_string) +class SingleLogoutService(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:SingleLogoutService element """ -class AssertionConsumerService(IndexedEndpoint): - """The md:AssertionConsumerService element""" - c_tag = 'AssertionConsumerService' - -def assertion_consumer_service_from_string(xml_string): - """ Create AssertionConsumerService instance from an XML string """ - return create_class_from_xml_string(AssertionConsumerService, xml_string) - - -class SingleLogoutService(Endpoint): - """The md:SingleLogoutService element""" c_tag = 'SingleLogoutService' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] def single_logout_service_from_string(xml_string): - """ Create SingleLogoutService instance from an XML string """ - return create_class_from_xml_string(SingleLogoutService, xml_string) + return saml2.create_class_from_xml_string(SingleLogoutService, xml_string) +class ManageNameIDService(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:ManageNameIDService element """ -class ManageNameIDService(Endpoint): - """The md:ManageNameIDService element""" c_tag = 'ManageNameIDService' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] def manage_name_id_service_from_string(xml_string): - """ Create ManageNameIDService instance from an XML string """ - return create_class_from_xml_string(ManageNameIDService, xml_string) - -# --------------------------------------------------------------------------- + return saml2.create_class_from_xml_string(ManageNameIDService, xml_string) class NameIDFormat(SamlBase): - """The md:NameIDFormat element""" - + """The urn:oasis:names:tc:SAML:2.0:metadata:NameIDFormat element """ + c_tag = 'NameIDFormat' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def name_id_format_from_string(xml_string): - """ Create NameIDFormat instance from an XML string """ - return create_class_from_xml_string(NameIDFormat, xml_string) + return saml2.create_class_from_xml_string(NameIDFormat, xml_string) -# --------------------------------------------------------------------------- +class SingleSignOnService(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:SingleSignOnService element """ -class EntityIDType(SamlBase): - """The md:entityIDType element""" - - c_tag = 'EntityIDType' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - -def entity_id_type_from_string(xml_string): - """ Create EntityIDType instance from an XML string """ - return create_class_from_xml_string(EntityIDType, xml_string) - -# --------------------------------------------------------------------------- - -class AffiliateMember(EntityIDType): - """The md:AffiliateMember element""" - - c_tag = 'AffiliateMember' - c_namespace = NAMESPACE - c_children = EntityIDType.c_children.copy() - c_attributes = EntityIDType.c_attributes.copy() - -def affiliate_member_from_string(xml_string): - """ Create AffiliateMember instance from an XML string """ - return create_class_from_xml_string(AffiliateMember, xml_string) - -# --------------------------------------------------------------------------- - -class PDPDescriptor(RoleDescriptor): - """The md:PDPDescriptor element""" - - c_tag = 'PDPDescriptor' - c_namespace = NAMESPACE - c_children = RoleDescriptor.c_children.copy() - c_attributes = RoleDescriptor.c_attributes.copy() - c_children['{%s}AuthnQueryService' % NAMESPACE] = ( - 'authn_query_service', [AuthnQueryService]) - c_children['{%s}AssertionIDRequestService' % NAMESPACE] = ( - 'assertion_id_request_service', [AssertionIDRequestService]) - c_children['{%s}NameIDFormat' % NAMESPACE] = ( - 'name_id_format', [NameIDFormat]) - c_child_order = RoleDescriptor.c_child_order[:] - c_child_order.extend(['authn_query_service', - 'assertion_id_request_service', - 'name_id_format']) - - def __init__(self, authn_query_service=None, - assertion_id_request_service=None, - name_id_format=None, id=None, valid_until=None, - cache_duration=None, protocol_support_enumeration=None, - error_url=None, signature=None, extensions=None, - key_descriptor=None, organization=None, - contact_person=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for SSODescriptor - - :param authn_query_service: ArtifactResolutionService elements - :param assertion_id_request_service: SingleLogoutService elements - :param name_id_format: NameIDFormat elements - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param protocol_support_enumeration: protocolSupportEnumeration attribute - :param error_url: errorURL attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param key_descriptor: KeyDescriptor elements - :param organization: Organization element - :param contact_person: ContactPerson elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - RoleDescriptor.__init__(self, id, valid_until, cache_duration, - protocol_support_enumeration, error_url, signature, - extensions, key_descriptor, organization, - contact_person, text, extension_elements, - extension_attributes) - - self.authn_query_service = authn_query_service or [] - self.assertion_id_request_service = assertion_id_request_service or [] - self.name_id_format = name_id_format or [] - -def pdp_descriptor_from_string(xml_string): - """ Create PDPDescriptor instance from an XML string """ - return create_class_from_xml_string(PDPDescriptor, xml_string) - -# --------------------------------------------------------------------------- - -class SSODescriptor(RoleDescriptor): - """The md:SSODescriptor element""" - - c_tag = 'SSODescriptor' - c_namespace = NAMESPACE - c_children = RoleDescriptor.c_children.copy() - c_attributes = RoleDescriptor.c_attributes.copy() - c_children['{%s}ArtifactResolutionService' % NAMESPACE] = ( - 'artifact_resolution_service', [ArtifactResolutionService]) - c_children['{%s}SingleLogoutService' % NAMESPACE] = ( - 'single_logout_service', [SingleLogoutService]) - c_children['{%s}ManageNameIDService' % NAMESPACE] = ( - 'manage_name_id_service', [ManageNameIDService]) - c_children['{%s}NameIDFormat' % NAMESPACE] = ( - 'name_id_format', [NameIDFormat]) - c_child_order = RoleDescriptor.c_child_order[:] - c_child_order.extend(['artifact_resolution_service', - 'single_logout_service', 'manage_name_id_service', - 'name_id_format']) - - def __init__(self, artifact_resolution_service=None, - single_logout_service=None, manage_name_id_service=None, - name_id_format=None, id=None, valid_until=None, - cache_duration=None, protocol_support_enumeration=None, - error_url=None, signature=None, extensions=None, - key_descriptor=None, organization=None, - contact_person=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for SSODescriptor - - :param artifact_resolution_service: ArtifactResolutionService elements - :param single_logout_service: SingleLogoutService elements - :param manage_name_id_service: ManageNameIDService elements - :param name_id_format: NameIDFormat elements - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param protocol_support_enumeration: protocolSupportEnumeration attribute - :param error_url: errorURL attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param key_descriptor: KeyDescriptor elements - :param organization: Organization element - :param contact_person: ContactPerson elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - RoleDescriptor.__init__(self, id, valid_until, cache_duration, - protocol_support_enumeration, error_url, signature, - extensions, key_descriptor, organization, - contact_person, text, extension_elements, - extension_attributes) - - self.artifact_resolution_service = artifact_resolution_service or [] - self.single_logout_service = single_logout_service or [] - self.manage_name_id_service = manage_name_id_service or [] - self.name_id_format = name_id_format or [] - -def sso_descriptor_from_string(xml_string): - """ Create SSODescriptor instance from an XML string """ - return create_class_from_xml_string(SSODescriptor, xml_string) - - -class SingleSignOnService(Endpoint): - """The md:SingleSignOnService element""" c_tag = 'SingleSignOnService' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] def single_sign_on_service_from_string(xml_string): - """ Create SingleSignOnService instance from an XML string """ - return create_class_from_xml_string(SingleSignOnService, xml_string) + return saml2.create_class_from_xml_string(SingleSignOnService, xml_string) +class NameIDMappingService(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:NameIDMappingService element """ -class NameIDMappingService(Endpoint): - """The md:NameIDMappingService element""" c_tag = 'NameIDMappingService' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] def name_id_mapping_service_from_string(xml_string): - """ Create NameIDMappingService instance from an XML string """ - return create_class_from_xml_string(NameIDMappingService, xml_string) + return saml2.create_class_from_xml_string(NameIDMappingService, xml_string) +class AssertionIDRequestService(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AssertionIDRequestService element """ -class AssertionIDRequestService(Endpoint): - """The md:AssertionIDRequestService element""" c_tag = 'AssertionIDRequestService' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] def assertion_id_request_service_from_string(xml_string): - """ Create AssertionIDRequestService instance from an XML string """ - return create_class_from_xml_string(AssertionIDRequestService, xml_string) - -class AttributeService(Endpoint): - """The md:AttributeService element""" - c_tag = 'AttributeService' - -def attribute_service_from_string(xml_string): - """ Create AttributeService instance from an XML string """ - return create_class_from_xml_string(AttributeService, xml_string) - -# ---------------------------------------------------------------------------- + return saml2.create_class_from_xml_string(AssertionIDRequestService, xml_string) class AttributeProfile(SamlBase): - """The md:AttributeProfile element""" - + """The urn:oasis:names:tc:SAML:2.0:metadata:AttributeProfile element """ + c_tag = 'AttributeProfile' c_namespace = NAMESPACE + c_value_type = 'anyURI' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def attribute_profile_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeProfile, xml_string) + +class AssertionConsumerService(IndexedEndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AssertionConsumerService element """ + + c_tag = 'AssertionConsumerService' + c_namespace = NAMESPACE + c_children = IndexedEndpointType.c_children.copy() + c_attributes = IndexedEndpointType.c_attributes.copy() + c_child_order = IndexedEndpointType.c_child_order[:] + +def assertion_consumer_service_from_string(xml_string): + return saml2.create_class_from_xml_string(AssertionConsumerService, xml_string) + +class ServiceName(localizedNameType): + """The urn:oasis:names:tc:SAML:2.0:metadata:ServiceName element """ + + c_tag = 'ServiceName' + c_namespace = NAMESPACE + c_children = localizedNameType.c_children.copy() + c_attributes = localizedNameType.c_attributes.copy() + c_child_order = localizedNameType.c_child_order[:] + +def service_name_from_string(xml_string): + return saml2.create_class_from_xml_string(ServiceName, xml_string) + +class ServiceDescription(localizedNameType): + """The urn:oasis:names:tc:SAML:2.0:metadata:ServiceDescription element """ + + c_tag = 'ServiceDescription' + c_namespace = NAMESPACE + c_children = localizedNameType.c_children.copy() + c_attributes = localizedNameType.c_attributes.copy() + c_child_order = localizedNameType.c_child_order[:] + +def service_description_from_string(xml_string): + return saml2.create_class_from_xml_string(ServiceDescription, xml_string) + +class RequestedAttributeType(saml.AttributeType): + """The urn:oasis:names:tc:SAML:2.0:metadata:RequestedAttributeType element """ + + c_tag = 'RequestedAttributeType' + c_namespace = NAMESPACE + c_children = saml.AttributeType.c_children.copy() + c_attributes = saml.AttributeType.c_attributes.copy() + c_child_order = saml.AttributeType.c_child_order[:] + c_attributes['isRequired'] = ('is_required', 'boolean', False) + + def __init__(self, + is_required=None, + friendly_name=None, + name=None, + name_format=None, + attribute_value=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + saml.AttributeType.__init__(self, + friendly_name=friendly_name, + name=name, + name_format=name_format, + attribute_value=attribute_value, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.is_required=is_required + +def requested_attribute_type_from_string(xml_string): + return saml2.create_class_from_xml_string(RequestedAttributeType, xml_string) + +class AuthnQueryService(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AuthnQueryService element """ + + c_tag = 'AuthnQueryService' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] + +def authn_query_service_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnQueryService, xml_string) + +class AuthzService(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AuthzService element """ + + c_tag = 'AuthzService' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] + +def authz_service_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthzService, xml_string) + +class AttributeService(EndpointType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AttributeService element """ + + c_tag = 'AttributeService' + c_namespace = NAMESPACE + c_children = EndpointType.c_children.copy() + c_attributes = EndpointType.c_attributes.copy() + c_child_order = EndpointType.c_child_order[:] + +def attribute_service_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeService, xml_string) + +class AffiliateMember(entityIDType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AffiliateMember element """ + + c_tag = 'AffiliateMember' + c_namespace = NAMESPACE + c_children = entityIDType.c_children.copy() + c_attributes = entityIDType.c_attributes.copy() + c_child_order = entityIDType.c_child_order[:] + +def affiliate_member_from_string(xml_string): + return saml2.create_class_from_xml_string(AffiliateMember, xml_string) + +class Extensions(ExtensionsType): + """The urn:oasis:names:tc:SAML:2.0:metadata:Extensions element """ + + c_tag = 'Extensions' + c_namespace = NAMESPACE + c_children = ExtensionsType.c_children.copy() + c_attributes = ExtensionsType.c_attributes.copy() + c_child_order = ExtensionsType.c_child_order[:] + +def extensions_from_string(xml_string): + return saml2.create_class_from_xml_string(Extensions, xml_string) + +class OrganizationType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:OrganizationType element """ + + c_tag = 'OrganizationType' + c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Extensions'] = ('extensions', Extensions) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}OrganizationName'] = ('organization_name', [OrganizationName]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}OrganizationDisplayName'] = ('organization_display_name', [OrganizationDisplayName]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}OrganizationURL'] = ('organization_url', [OrganizationURL]) + c_child_order.extend(['extensions', 'organization_name', 'organization_display_name', 'organization_url']) -def attribute_profile_from_string(xml_string): - """ Create AttributeProfile instance from an XML string """ - return create_class_from_xml_string(AttributeProfile, xml_string) + def __init__(self, + extensions=None, + organization_name=None, + organization_display_name=None, + organization_url=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.extensions=extensions + self.organization_name=organization_name or [] + self.organization_display_name=organization_display_name or [] + self.organization_url=organization_url or [] -# ---------------------------------------------------------------------------- +def organization_type_from_string(xml_string): + return saml2.create_class_from_xml_string(OrganizationType, xml_string) -class IDPSSODescriptor(SSODescriptor): - """The md:IDPSSODescriptor element""" +class ContactType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:ContactType element """ - c_tag = 'IDPSSODescriptor' + c_tag = 'ContactType' c_namespace = NAMESPACE - c_children = SSODescriptor.c_children.copy() - c_attributes = SSODescriptor.c_attributes.copy() - c_attributes['WantAuthnRequestsSigned'] = 'want_authn_requests_signed' - c_children['{%s}SingleSignOnService' % NAMESPACE] = ( - 'single_sign_on_service', [SingleSignOnService]) - c_children['{%s}NameIDMappingService' % NAMESPACE] = ( - 'name_id_mapping_service', [NameIDMappingService]) - c_children['{%s}AssertionIDRequestService' % NAMESPACE] = ( - 'assertion_id_request_service', [AssertionIDRequestService]) - c_children['{%s}AttributeProfile' % NAMESPACE] = ( - 'attribute_profile', [AttributeProfile]) - c_children['{%s}Attribute' % SAML_NAMESPACE] = ( - 'attribute', [Attribute]) + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Extensions'] = ('extensions', Extensions) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Company'] = ('company', Company) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}GivenName'] = ('given_name', GivenName) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}SurName'] = ('sur_name', SurName) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}EmailAddress'] = ('email_address', [EmailAddress]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}TelephoneNumber'] = ('telephone_number', [TelephoneNumber]) + c_attributes['contactType'] = ('contact_type', 'ContactTypeType', True) + c_child_order.extend(['extensions', 'company', 'given_name', 'sur_name', 'email_address', 'telephone_number']) - c_child_order = SSODescriptor.c_child_order[:] - c_child_order.extend(['single_sign_on_service', 'name_id_mapping_service', - 'assertion_id_request_service', 'attribute_profile', - 'attribute']) + def __init__(self, + extensions=None, + company=None, + given_name=None, + sur_name=None, + email_address=None, + telephone_number=None, + contact_type=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.extensions=extensions + self.company=company + self.given_name=given_name + self.sur_name=sur_name + self.email_address=email_address or [] + self.telephone_number=telephone_number or [] + self.contact_type=contact_type - def __init__(self, want_authn_requests_signed=None, - single_sign_on_service=None, name_id_mapping_service=None, - assertion_id_request_service=None, attribute_profile=None, - attribute=None, artifact_resolution_service=None, - single_logout_service=None, manage_name_id_service=None, - name_id_format=None, - id=None, valid_until=None, cache_duration=None, - protocol_support_enumeration=None, error_url=None, - signature=None, extensions=None, key_descriptor=None, - organization=None, contact_person=None, - text=None, - extension_elements=None, extension_attributes=None): - """Constructor for IDPSSODescriptor +def contact_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ContactType, xml_string) - :param want_authn_requests_signed: WantAuthnRequestsSigned attribute - :param single_sign_on_service: SingleSignOnService elements - :param name_id_mapping_service: NameIDMappingService elements - :param assertion_id_request_service: AssertionIDRequestService elements - :param attribute_profile: AttributeProfile elements - :param attribute: Attribute elements - :param artifact_resolution_service: ArtifactResolutionService elements - :param single_logout_service: SingleLogoutService elements - :param manage_name_id_service: ManageNameIDService elements - :param name_id_format: NameIDFormat elements - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param protocol_support_enumeration: protocolSupportEnumeration attribute - :param error_url: errorURL attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param key_descriptor: KeyDescriptor elements - :param organization: Organization element - :param contact_person: ContactPerson elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SSODescriptor.__init__(self, artifact_resolution_service, - single_logout_service, manage_name_id_service, - name_id_format, id, valid_until, - cache_duration, protocol_support_enumeration, - error_url, signature, extensions, key_descriptor, - organization, contact_person, text, extension_elements, - extension_attributes) +class AdditionalMetadataLocation(AdditionalMetadataLocationType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AdditionalMetadataLocation element """ - self.want_authn_requests_signed = want_authn_requests_signed - self.single_sign_on_service = single_sign_on_service or [] - self.name_id_mapping_service = name_id_mapping_service or [] - self.assertion_id_request_service = assertion_id_request_service or [] - self.attribute_profile = attribute_profile or [] - self.attribute = attribute or [] + c_tag = 'AdditionalMetadataLocation' + c_namespace = NAMESPACE + c_children = AdditionalMetadataLocationType.c_children.copy() + c_attributes = AdditionalMetadataLocationType.c_attributes.copy() + c_child_order = AdditionalMetadataLocationType.c_child_order[:] -def idpsso_descriptor_from_string(xml_string): - """ Create IDPSSODescriptor instance from an XML string """ - return create_class_from_xml_string(IDPSSODescriptor, xml_string) +def additional_metadata_location_from_string(xml_string): + return saml2.create_class_from_xml_string(AdditionalMetadataLocation, xml_string) +class KeyDescriptorType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:KeyDescriptorType element """ -class RequestedAttribute(Attribute): + c_tag = 'KeyDescriptorType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', ds.KeyInfo) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}EncryptionMethod'] = ('encryption_method', [EncryptionMethod]) + c_attributes['use'] = ('use', 'KeyTypes', False) + c_child_order.extend(['key_info', 'encryption_method']) + + def __init__(self, + key_info=None, + encryption_method=None, + use=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.key_info=key_info + self.encryption_method=encryption_method or [] + self.use=use + +def key_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(KeyDescriptorType, xml_string) + +class RequestedAttribute(RequestedAttributeType): + """The urn:oasis:names:tc:SAML:2.0:metadata:RequestedAttribute element """ c_tag = 'RequestedAttribute' c_namespace = NAMESPACE - c_children = Attribute.c_children.copy() - c_attributes = Attribute.c_attributes.copy() - c_attributes['isRequired'] = 'is_required' - - def __init__(self, is_required=None, name=None, name_format=None, - friendly_name=None, attribute_value=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for RequestedAttribute - - :param is_required: isRequired attribute - :param name: Name attribute - :param name_format: NameFormat attribute - :param friendly_name: FriendlyName attribute - :param attribute_value: AttributeValue elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - Attribute.__init__(self, name, name_format, friendly_name, - attribute_value, text, extension_elements, - extension_attributes) - self.is_required = is_required + c_children = RequestedAttributeType.c_children.copy() + c_attributes = RequestedAttributeType.c_attributes.copy() + c_child_order = RequestedAttributeType.c_child_order[:] def requested_attribute_from_string(xml_string): - """ Create RequestedAttribute instance from an XML string """ - return create_class_from_xml_string(RequestedAttribute, xml_string) + return saml2.create_class_from_xml_string(RequestedAttribute, xml_string) +class Organization(OrganizationType): + """The urn:oasis:names:tc:SAML:2.0:metadata:Organization element """ -class ServiceName(LocalizedName): - """The md:ServiceName element""" - c_tag = 'ServiceName' + c_tag = 'Organization' c_namespace = NAMESPACE - c_children = LocalizedName.c_children.copy() - c_attributes = LocalizedName.c_attributes.copy() + c_children = OrganizationType.c_children.copy() + c_attributes = OrganizationType.c_attributes.copy() + c_child_order = OrganizationType.c_child_order[:] - def __init__(self, lang=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for ServiceName +def organization_from_string(xml_string): + return saml2.create_class_from_xml_string(Organization, xml_string) - :param lang: xml:lang attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +class ContactPerson(ContactType): + """The urn:oasis:names:tc:SAML:2.0:metadata:ContactPerson element """ - LocalizedName.__init__(self, lang, text, extension_elements, - extension_attributes) - -def service_name_from_string(xml_string): - """ Create ServiceName instance from an XML string """ - return create_class_from_xml_string(ServiceName, xml_string) - - -class ServiceDescription(LocalizedName): - """The md:ServiceDescription element""" - c_tag = 'ServiceDescription' + c_tag = 'ContactPerson' c_namespace = NAMESPACE - c_children = LocalizedName.c_children.copy() - c_attributes = LocalizedName.c_attributes.copy() + c_children = ContactType.c_children.copy() + c_attributes = ContactType.c_attributes.copy() + c_child_order = ContactType.c_child_order[:] - def __init__(self, lang=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for ServiceDescription +def contact_person_from_string(xml_string): + return saml2.create_class_from_xml_string(ContactPerson, xml_string) - :param lang: xml:lang attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +class KeyDescriptor(KeyDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:KeyDescriptor element """ - LocalizedName.__init__(self, lang, text, extension_elements, - extension_attributes) + c_tag = 'KeyDescriptor' + c_namespace = NAMESPACE + c_children = KeyDescriptorType.c_children.copy() + c_attributes = KeyDescriptorType.c_attributes.copy() + c_child_order = KeyDescriptorType.c_child_order[:] -def service_description_from_string(xml_string): - """ Create ServiceDescription instance from an XML string """ - return create_class_from_xml_string(ServiceDescription, xml_string) +def key_descriptor_from_string(xml_string): + return saml2.create_class_from_xml_string(KeyDescriptor, xml_string) +class RoleDescriptorType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:RoleDescriptorType element """ + + c_tag = 'RoleDescriptorType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Extensions'] = ('extensions', Extensions) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}KeyDescriptor'] = ('key_descriptor', [KeyDescriptor]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Organization'] = ('organization', Organization) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}ContactPerson'] = ('contact_person', [ContactPerson]) + c_attributes['ID'] = ('id', 'ID', False) + c_attributes['validUntil'] = ('valid_until', 'dateTime', False) + c_attributes['cacheDuration'] = ('cache_duration', 'duration', False) + c_attributes['protocolSupportEnumeration'] = ('protocol_support_enumeration', 'anyURIListType', True) + c_attributes['errorURL'] = ('error_url', 'anyURI', False) + c_child_order.extend(['signature', 'extensions', 'key_descriptor', 'organization', 'contact_person']) + + def __init__(self, + signature=None, + extensions=None, + key_descriptor=None, + organization=None, + contact_person=None, + id=None, + valid_until=None, + cache_duration=None, + protocol_support_enumeration=None, + error_url=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.signature=signature + self.extensions=extensions + self.key_descriptor=key_descriptor or [] + self.organization=organization + self.contact_person=contact_person or [] + self.id=id + self.valid_until=valid_until + self.cache_duration=cache_duration + self.protocol_support_enumeration=protocol_support_enumeration + self.error_url=error_url + +def role_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(RoleDescriptorType, xml_string) + +class SSODescriptorType(RoleDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:SSODescriptorType element """ + + c_tag = 'SSODescriptorType' + c_namespace = NAMESPACE + c_children = RoleDescriptorType.c_children.copy() + c_attributes = RoleDescriptorType.c_attributes.copy() + c_child_order = RoleDescriptorType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}ArtifactResolutionService'] = ('artifact_resolution_service', [ArtifactResolutionService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}SingleLogoutService'] = ('single_logout_service', [SingleLogoutService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}ManageNameIDService'] = ('manage_name_id_service', [ManageNameIDService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}NameIDFormat'] = ('name_id_format', [NameIDFormat]) + c_child_order.extend(['artifact_resolution_service', 'single_logout_service', 'manage_name_id_service', 'name_id_format']) + + def __init__(self, + artifact_resolution_service=None, + single_logout_service=None, + manage_name_id_service=None, + name_id_format=None, + signature=None, + extensions=None, + key_descriptor=None, + organization=None, + contact_person=None, + id=None, + valid_until=None, + cache_duration=None, + protocol_support_enumeration=None, + error_url=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RoleDescriptorType.__init__(self, + signature=signature, + extensions=extensions, + key_descriptor=key_descriptor, + organization=organization, + contact_person=contact_person, + id=id, + valid_until=valid_until, + cache_duration=cache_duration, + protocol_support_enumeration=protocol_support_enumeration, + error_url=error_url, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.artifact_resolution_service=artifact_resolution_service or [] + self.single_logout_service=single_logout_service or [] + self.manage_name_id_service=manage_name_id_service or [] + self.name_id_format=name_id_format or [] + +def sso_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SSODescriptorType, xml_string) + +class IDPSSODescriptorType(SSODescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:IDPSSODescriptorType element """ + + c_tag = 'IDPSSODescriptorType' + c_namespace = NAMESPACE + c_children = SSODescriptorType.c_children.copy() + c_attributes = SSODescriptorType.c_attributes.copy() + c_child_order = SSODescriptorType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}SingleSignOnService'] = ('single_sign_on_service', [SingleSignOnService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}NameIDMappingService'] = ('name_id_mapping_service', [NameIDMappingService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AssertionIDRequestService'] = ('assertion_id_request_service', [AssertionIDRequestService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AttributeProfile'] = ('attribute_profile', [AttributeProfile]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ('attribute', [saml.Attribute]) + c_attributes['WantAuthnRequestsSigned'] = ('want_authn_requests_signed', 'boolean', False) + c_child_order.extend(['single_sign_on_service', 'name_id_mapping_service', 'assertion_id_request_service', 'attribute_profile', 'attribute']) + + def __init__(self, + single_sign_on_service=None, + name_id_mapping_service=None, + assertion_id_request_service=None, + attribute_profile=None, + attribute=None, + want_authn_requests_signed=None, + artifact_resolution_service=None, + single_logout_service=None, + manage_name_id_service=None, + name_id_format=None, + signature=None, + extensions=None, + key_descriptor=None, + organization=None, + contact_person=None, + id=None, + valid_until=None, + cache_duration=None, + protocol_support_enumeration=None, + error_url=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SSODescriptorType.__init__(self, + artifact_resolution_service=artifact_resolution_service, + single_logout_service=single_logout_service, + manage_name_id_service=manage_name_id_service, + name_id_format=name_id_format, + signature=signature, + extensions=extensions, + key_descriptor=key_descriptor, + organization=organization, + contact_person=contact_person, + id=id, + valid_until=valid_until, + cache_duration=cache_duration, + protocol_support_enumeration=protocol_support_enumeration, + error_url=error_url, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.single_sign_on_service=single_sign_on_service or [] + self.name_id_mapping_service=name_id_mapping_service or [] + self.assertion_id_request_service=assertion_id_request_service or [] + self.attribute_profile=attribute_profile or [] + self.attribute=attribute or [] + self.want_authn_requests_signed=want_authn_requests_signed + +def idpsso_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(IDPSSODescriptorType, xml_string) + +class AttributeConsumingServiceType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:AttributeConsumingServiceType element """ + + c_tag = 'AttributeConsumingServiceType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}ServiceName'] = ('service_name', [ServiceName]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}ServiceDescription'] = ('service_description', [ServiceDescription]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}RequestedAttribute'] = ('requested_attribute', [RequestedAttribute]) + c_attributes['index'] = ('index', 'unsignedShort', True) + c_attributes['isDefault'] = ('is_default', 'boolean', False) + c_child_order.extend(['service_name', 'service_description', 'requested_attribute']) + + def __init__(self, + service_name=None, + service_description=None, + requested_attribute=None, + index=None, + is_default=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.service_name=service_name or [] + self.service_description=service_description or [] + self.requested_attribute=requested_attribute or [] + self.index=index + self.is_default=is_default + +def attribute_consuming_service_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeConsumingServiceType, xml_string) + +class AuthnAuthorityDescriptorType(RoleDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AuthnAuthorityDescriptorType element """ + + c_tag = 'AuthnAuthorityDescriptorType' + c_namespace = NAMESPACE + c_children = RoleDescriptorType.c_children.copy() + c_attributes = RoleDescriptorType.c_attributes.copy() + c_child_order = RoleDescriptorType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AuthnQueryService'] = ('authn_query_service', [AuthnQueryService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AssertionIDRequestService'] = ('assertion_id_request_service', [AssertionIDRequestService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}NameIDFormat'] = ('name_id_format', [NameIDFormat]) + c_child_order.extend(['authn_query_service', 'assertion_id_request_service', 'name_id_format']) + + def __init__(self, + authn_query_service=None, + assertion_id_request_service=None, + name_id_format=None, + signature=None, + extensions=None, + key_descriptor=None, + organization=None, + contact_person=None, + id=None, + valid_until=None, + cache_duration=None, + protocol_support_enumeration=None, + error_url=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RoleDescriptorType.__init__(self, + signature=signature, + extensions=extensions, + key_descriptor=key_descriptor, + organization=organization, + contact_person=contact_person, + id=id, + valid_until=valid_until, + cache_duration=cache_duration, + protocol_support_enumeration=protocol_support_enumeration, + error_url=error_url, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.authn_query_service=authn_query_service or [] + self.assertion_id_request_service=assertion_id_request_service or [] + self.name_id_format=name_id_format or [] + +def authn_authority_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnAuthorityDescriptorType, xml_string) + +class PDPDescriptorType(RoleDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:PDPDescriptorType element """ + + c_tag = 'PDPDescriptorType' + c_namespace = NAMESPACE + c_children = RoleDescriptorType.c_children.copy() + c_attributes = RoleDescriptorType.c_attributes.copy() + c_child_order = RoleDescriptorType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AuthzService'] = ('authz_service', [AuthzService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AssertionIDRequestService'] = ('assertion_id_request_service', [AssertionIDRequestService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}NameIDFormat'] = ('name_id_format', [NameIDFormat]) + c_child_order.extend(['authz_service', 'assertion_id_request_service', 'name_id_format']) + + def __init__(self, + authz_service=None, + assertion_id_request_service=None, + name_id_format=None, + signature=None, + extensions=None, + key_descriptor=None, + organization=None, + contact_person=None, + id=None, + valid_until=None, + cache_duration=None, + protocol_support_enumeration=None, + error_url=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RoleDescriptorType.__init__(self, + signature=signature, + extensions=extensions, + key_descriptor=key_descriptor, + organization=organization, + contact_person=contact_person, + id=id, + valid_until=valid_until, + cache_duration=cache_duration, + protocol_support_enumeration=protocol_support_enumeration, + error_url=error_url, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.authz_service=authz_service or [] + self.assertion_id_request_service=assertion_id_request_service or [] + self.name_id_format=name_id_format or [] + +def pdp_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(PDPDescriptorType, xml_string) + +class AttributeAuthorityDescriptorType(RoleDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AttributeAuthorityDescriptorType element """ + + c_tag = 'AttributeAuthorityDescriptorType' + c_namespace = NAMESPACE + c_children = RoleDescriptorType.c_children.copy() + c_attributes = RoleDescriptorType.c_attributes.copy() + c_child_order = RoleDescriptorType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AttributeService'] = ('attribute_service', [AttributeService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AssertionIDRequestService'] = ('assertion_id_request_service', [AssertionIDRequestService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}NameIDFormat'] = ('name_id_format', [NameIDFormat]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AttributeProfile'] = ('attribute_profile', [AttributeProfile]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ('attribute', [saml.Attribute]) + c_child_order.extend(['attribute_service', 'assertion_id_request_service', 'name_id_format', 'attribute_profile', 'attribute']) + + def __init__(self, + attribute_service=None, + assertion_id_request_service=None, + name_id_format=None, + attribute_profile=None, + attribute=None, + signature=None, + extensions=None, + key_descriptor=None, + organization=None, + contact_person=None, + id=None, + valid_until=None, + cache_duration=None, + protocol_support_enumeration=None, + error_url=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RoleDescriptorType.__init__(self, + signature=signature, + extensions=extensions, + key_descriptor=key_descriptor, + organization=organization, + contact_person=contact_person, + id=id, + valid_until=valid_until, + cache_duration=cache_duration, + protocol_support_enumeration=protocol_support_enumeration, + error_url=error_url, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.attribute_service=attribute_service or [] + self.assertion_id_request_service=assertion_id_request_service or [] + self.name_id_format=name_id_format or [] + self.attribute_profile=attribute_profile or [] + self.attribute=attribute or [] + +def attribute_authority_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeAuthorityDescriptorType, xml_string) + +class AffiliationDescriptorType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:AffiliationDescriptorType element """ + + c_tag = 'AffiliationDescriptorType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Extensions'] = ('extensions', Extensions) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AffiliateMember'] = ('affiliate_member', [AffiliateMember]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}KeyDescriptor'] = ('key_descriptor', [KeyDescriptor]) + c_attributes['affiliationOwnerID'] = ('affiliation_owner_id', 'entityIDType', True) + c_attributes['validUntil'] = ('valid_until', 'dateTime', False) + c_attributes['cacheDuration'] = ('cache_duration', 'duration', False) + c_attributes['ID'] = ('id', 'ID', False) + c_child_order.extend(['signature', 'extensions', 'affiliate_member', 'key_descriptor']) + + def __init__(self, + signature=None, + extensions=None, + affiliate_member=None, + key_descriptor=None, + affiliation_owner_id=None, + valid_until=None, + cache_duration=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.signature=signature + self.extensions=extensions + self.affiliate_member=affiliate_member or [] + self.key_descriptor=key_descriptor or [] + self.affiliation_owner_id=affiliation_owner_id + self.valid_until=valid_until + self.cache_duration=cache_duration + self.id=id + +def affiliation_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AffiliationDescriptorType, xml_string) + +class RoleDescriptor(RoleDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:RoleDescriptor element """ + + c_tag = 'RoleDescriptor' + c_namespace = NAMESPACE + c_children = RoleDescriptorType.c_children.copy() + c_attributes = RoleDescriptorType.c_attributes.copy() + c_child_order = RoleDescriptorType.c_child_order[:] + +def role_descriptor_from_string(xml_string): + return saml2.create_class_from_xml_string(RoleDescriptor, xml_string) + +class IDPSSODescriptor(IDPSSODescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:IDPSSODescriptor element """ + + c_tag = 'IDPSSODescriptor' + c_namespace = NAMESPACE + c_children = IDPSSODescriptorType.c_children.copy() + c_attributes = IDPSSODescriptorType.c_attributes.copy() + c_child_order = IDPSSODescriptorType.c_child_order[:] + +def idpsso_descriptor_from_string(xml_string): + return saml2.create_class_from_xml_string(IDPSSODescriptor, xml_string) + +class AttributeConsumingService(AttributeConsumingServiceType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AttributeConsumingService element """ -class AttributeConsumingService(SamlBase): - """The md:AttributeConsumingService element""" - c_tag = 'AttributeConsumingService' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['index'] = 'index' - c_attributes['isDefault'] = 'is_default' - c_required_attributes = ["index"] - c_children['{%s}ServiceName' % NAMESPACE] = ( - 'service_name', [ServiceName]) - c_children['{%s}ServiceDescription' % NAMESPACE] = ( - 'service_description', [ServiceDescription]) - c_children['{%s}RequestedAttribute' % NAMESPACE] = ( - 'requested_attribute', [RequestedAttribute]) - c_child_order = ['service_name', 'service_description', - 'requested_attribute'] - - def __init__(self, index=None, is_default=None, service_name=None, - service_description=None, requested_attribute=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AttributeConsumingService - - :param index: index attribute - :param is_default: isDefault attribute - :param service_name: ServiceName elements - :param service_descriptor: ServiceDescriptor elements - :param requested_attribute: RequestedAttribute elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.index = index - self.is_default = is_default - self.service_name = service_name or [] - self.service_description = service_description or [] - self.requested_attribute = requested_attribute or [] + c_children = AttributeConsumingServiceType.c_children.copy() + c_attributes = AttributeConsumingServiceType.c_attributes.copy() + c_child_order = AttributeConsumingServiceType.c_child_order[:] def attribute_consuming_service_from_string(xml_string): - """ Create AttributeConsumingService instance from an XML string """ - return create_class_from_xml_string(AttributeConsumingService, xml_string) + return saml2.create_class_from_xml_string(AttributeConsumingService, xml_string) - -class SPSSODescriptor(SSODescriptor): - """The md:SPSSODescriptor element""" - - c_tag = 'SPSSODescriptor' - c_namespace = NAMESPACE - c_children = SSODescriptor.c_children.copy() - c_attributes = SSODescriptor.c_attributes.copy() - c_attributes['AuthnRequestsSigned'] = 'authn_requests_signed' - c_attributes['WantAssertionsSigned'] = 'want_assertions_signed' - c_children['{%s}AssertionConsumerService' % NAMESPACE] = ( - 'assertion_consumer_service', [AssertionConsumerService]) - c_children['{%s}AttributeConsumingService' % NAMESPACE] = ( - 'attribute_consuming_service', [AttributeConsumingService]) - - c_child_order = SSODescriptor.c_child_order[:] - c_child_order.extend(['assertion_consumer_service', - 'attribute_consuming_service']) - - def __init__(self, id=None, valid_until=None, cache_duration=None, - protocol_support_enumeration=None, error_url=None, - signature=None, extensions=None, key_descriptor=None, - organization=None, contact_person=None, - artifact_resolution_service=None, - single_logout_service=None, manage_name_id_service=None, - name_id_format=None, authn_requests_signed=None, - want_assertions_signed=None, - assertion_consumer_service=None, - attribute_consuming_service=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for IDPSSODescriptor - - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param protocol_support_enumeration: protocolSupportEnumeration - attribute - :param error_url: errorURL attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param key_descriptor: KeyDescriptor elements - :param organization: Organization element - :param contact_person: ContactPerson elements - :param artifact_resolution_service: ArtifactResolutionService elements - :param single_logout_service: SingleLogoutService elements - :param manage_name_id_service: ManageNameIDService elements - :param name_id_format: NameIDFormat elements - :param authn_requests_signed: AuthnRequestsSigned attribute - :param want_assertions_signed: WantAssertionsSigned attribute - :param assertion_consumer_service: AssertionConsumerService elements - :param attribute_consuming_service: AttributeConsumingService elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - SSODescriptor.__init__(self, artifact_resolution_service, - single_logout_service, manage_name_id_service, - name_id_format, id, valid_until, - cache_duration, protocol_support_enumeration, - error_url, signature, - extensions, key_descriptor, organization, - contact_person, text, extension_elements, - extension_attributes) - - self.authn_requests_signed = authn_requests_signed - self.want_assertions_signed = want_assertions_signed - self.assertion_consumer_service = assertion_consumer_service or [] - self.attribute_consuming_service = attribute_consuming_service or [] - -def spsso_descriptor_from_string(xml_string): - """ Create SPSSODescriptor instance from an XML string """ - return create_class_from_xml_string(SPSSODescriptor, xml_string) - -# ---------------------------------------------------------------------------- - -class AttributeAuthorityDescriptor(RoleDescriptor): - """The md:AttributeAuthorityDescriptor element""" - - c_tag = 'AttributeAuthorityDescriptor' - c_namespace = NAMESPACE - c_children = RoleDescriptor.c_children.copy() - c_attributes = RoleDescriptor.c_attributes.copy() - c_child_order = RoleDescriptor.c_child_order[:] - - c_children['{%s}AttributeService' % NAMESPACE] = ( - 'attribute_service', [AttributeService]) - c_children['{%s}AssertionIDRequestService' % NAMESPACE] = ( - 'assertion_id_request_service', [AssertionIDRequestService]) - c_children['{%s}NameIDFormat' % NAMESPACE] = ( - 'name_id_format', [NameIDFormat]) - c_children['{%s}AttributeProfile' % NAMESPACE] = ( - 'attribute_profile', [AttributeProfile]) - c_children['{%s}Attribute' % saml.NAMESPACE] = ( - 'attribute', [saml.Attribute]) - - c_child_order.extend(["attribute_service", "assertion_id_request_service", - "name_id_format", "attribute_profile", - "attribute"]) - - def __init__(self, attribute_service=None, - assertion_id_request_service=None, name_id_format=None, - attribute_profile=None, attribute=None, - id=None, valid_until=None, - cache_duration=None, protocol_support_enumeration=None, - error_url=None, signature=None, extensions=None, - key_descriptor=None, organization=None, - contact_person=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AttributeAuthorityDescriptor - - :param attribute_service: ArtifactResolutionService elements - :param assertion_id_request_service: SingleLogoutService elements - :param name_id_format: NameIDFormat elements - :param attribute_profile: - :param attribute: - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param protocol_support_enumeration: protocolSupportEnumeration attribute - :param error_url: errorURL attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param key_descriptor: KeyDescriptor elements - :param organization: Organization element - :param contact_person: ContactPerson elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - RoleDescriptor.__init__(self, id, valid_until, cache_duration, - protocol_support_enumeration, error_url, signature, - extensions, key_descriptor, organization, - contact_person, text, extension_elements, - extension_attributes) - - self.attribute_service = attribute_service or [] - self.assertion_id_request_service = assertion_id_request_service or [] - self.name_id_format = name_id_format or [] - self.attribute_profile = attribute_profile or [] - self.attribute = attribute or [] - -def attribute_authority_descriptor_from_string(xml_string): - """ Create AttributeAuthorityDescriptor instance from an XML string """ - return create_class_from_xml_string(AttributeAuthorityDescriptor, - xml_string) - -# --------------------------------------------------------------------------- - -class AffiliationDescriptor(SamlBase): - """The md:AffiliationDescriptor element""" - - c_tag = 'AffiliationDescriptor' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['affiliationOwnerID'] = 'affiliation_owner_id' - c_attributes['ID'] = 'id' - c_attributes['validUntil'] = 'valid_until' - c_attributes['cacheDuration'] = 'cache_duration' - c_required_attributes = ["affiliation_owner_id"] - c_children['{%s}Signature' % DS_NAMESPACE] = ('signature', ds.Signature) - c_children['{%s}Extensions' % NAMESPACE] = ('extensions', Extensions) - c_children['{%s}AffiliateMember' % NAMESPACE] = ( - 'affiliate_member', [AffiliateMember]) - c_children['{%s}KeyDescriptor' % NAMESPACE] = ( - 'key_descriptor', [KeyDescriptor]) - c_child_order = ['signature', 'extensions', 'affiliate_member', - 'key_descriptor'] - - def __init__(self, affiliation_owner_id=None, id=None, - valid_until=None, cache_duration=None, - signature=None, extensions=None, - affiliate_member=None, key_descriptor=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AffiliationDescriptor - - :param affiliation_owner_id: entityID attribute - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param affiliate_member: RoleDescriptor elements - :param key_descriptor: IDPSSODescriptor elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.affiliation_owner_id = affiliation_owner_id - self.id = id - self.valid_until = valid_until - self.cache_duration = cache_duration - self.signature = signature - self.extensions = extensions - self.affiliate_member = affiliate_member or [] - self.key_descriptor = key_descriptor or [] - -def affiliation_descriptor_from_string(xml_string): - """ Create AffiliationDescriptor instance from an XML string """ - return create_class_from_xml_string(AffiliationDescriptor, xml_string) - -# --------------------------------------------------------------------------- - -class AuthnAuthorityDescriptor(RoleDescriptor): +class AuthnAuthorityDescriptor(AuthnAuthorityDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AuthnAuthorityDescriptor element """ c_tag = 'AuthnAuthorityDescriptor' c_namespace = NAMESPACE - c_children = RoleDescriptor.c_children.copy() - c_attributes = RoleDescriptor.c_attributes.copy() + c_children = AuthnAuthorityDescriptorType.c_children.copy() + c_attributes = AuthnAuthorityDescriptorType.c_attributes.copy() + c_child_order = AuthnAuthorityDescriptorType.c_child_order[:] - - c_children['{%s}AuthnQueryService' % NAMESPACE] = ( - 'authn_query_service', AuthnQueryService) - c_children['{%s}AssertionIDRequestService' % NAMESPACE] = ( - 'assertion_id_request_service', AssertionIDRequestService) - c_children['{%s}NameIDFormat' % NAMESPACE] = ( - 'name_id_format', NameIDFormat) - c_child_order = RoleDescriptor.c_child_order[:] - c_child_order.extend(["authn_query_service", - "assertion_id_request_service", "name_id_format"]) - - def __init__(self, authn_query_service=None, - assertion_id_request_service=None, name_id_format=None, - attribute_profile=None, attribute=None, - id=None, valid_until=None, - cache_duration=None, protocol_support_enumeration=None, - error_url=None, signature=None, extensions=None, - key_descriptor=None, organization=None, - contact_person=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AttributeAuthorityDescriptor - - :param authn_query_service: ArtifactResolutionService elements - :param assertion_id_request_service: SingleLogoutService elements - :param name_id_format: NameIDFormat elements - :param attribute_profile: - :param attribute: - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param protocol_support_enumeration: protocolSupportEnumeration attribute - :param error_url: errorURL attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param key_descriptor: KeyDescriptor elements - :param organization: Organization element - :param contact_person: ContactPerson elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - RoleDescriptor.__init__(self, id, valid_until, cache_duration, - protocol_support_enumeration, error_url, signature, - extensions, key_descriptor, organization, - contact_person, text, extension_elements, - extension_attributes) - - self.authn_query_service = authn_query_service or [] - self.assertion_id_request_service = assertion_id_request_service or [] - self.name_id_format = name_id_format or [] - def authn_authority_descriptor_from_string(xml_string): - """ Create AuthnAuthorityDescriptor instance from an XML string """ - return create_class_from_xml_string(AuthnAuthorityDescriptor, xml_string) + return saml2.create_class_from_xml_string(AuthnAuthorityDescriptor, xml_string) -# --------------------------------------------------------------------------- +class PDPDescriptor(PDPDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:PDPDescriptor element """ + c_tag = 'PDPDescriptor' + c_namespace = NAMESPACE + c_children = PDPDescriptorType.c_children.copy() + c_attributes = PDPDescriptorType.c_attributes.copy() + c_child_order = PDPDescriptorType.c_child_order[:] -class EntityDescriptor(SamlBase): - """The md:EntityDescriptor element""" - # TODO: AuthnAuthorityDescriptor, AttributeAuthorityDescriptor, - # PDPDescriptor, +def pdp_descriptor_from_string(xml_string): + return saml2.create_class_from_xml_string(PDPDescriptor, xml_string) + +class AttributeAuthorityDescriptor(AttributeAuthorityDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AttributeAuthorityDescriptor element """ + + c_tag = 'AttributeAuthorityDescriptor' + c_namespace = NAMESPACE + c_children = AttributeAuthorityDescriptorType.c_children.copy() + c_attributes = AttributeAuthorityDescriptorType.c_attributes.copy() + c_child_order = AttributeAuthorityDescriptorType.c_child_order[:] + +def attribute_authority_descriptor_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeAuthorityDescriptor, xml_string) + +class AffiliationDescriptor(AffiliationDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:AffiliationDescriptor element """ + + c_tag = 'AffiliationDescriptor' + c_namespace = NAMESPACE + c_children = AffiliationDescriptorType.c_children.copy() + c_attributes = AffiliationDescriptorType.c_attributes.copy() + c_child_order = AffiliationDescriptorType.c_child_order[:] + +def affiliation_descriptor_from_string(xml_string): + return saml2.create_class_from_xml_string(AffiliationDescriptor, xml_string) + +class SPSSODescriptorType(SSODescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:SPSSODescriptorType element """ + + c_tag = 'SPSSODescriptorType' + c_namespace = NAMESPACE + c_children = SSODescriptorType.c_children.copy() + c_attributes = SSODescriptorType.c_attributes.copy() + c_child_order = SSODescriptorType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AssertionConsumerService'] = ('assertion_consumer_service', [AssertionConsumerService]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AttributeConsumingService'] = ('attribute_consuming_service', [AttributeConsumingService]) + c_attributes['AuthnRequestsSigned'] = ('authn_requests_signed', 'boolean', False) + c_attributes['WantAssertionsSigned'] = ('want_assertions_signed', 'boolean', False) + c_child_order.extend(['assertion_consumer_service', 'attribute_consuming_service']) + + def __init__(self, + assertion_consumer_service=None, + attribute_consuming_service=None, + authn_requests_signed=None, + want_assertions_signed=None, + artifact_resolution_service=None, + single_logout_service=None, + manage_name_id_service=None, + name_id_format=None, + signature=None, + extensions=None, + key_descriptor=None, + organization=None, + contact_person=None, + id=None, + valid_until=None, + cache_duration=None, + protocol_support_enumeration=None, + error_url=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SSODescriptorType.__init__(self, + artifact_resolution_service=artifact_resolution_service, + single_logout_service=single_logout_service, + manage_name_id_service=manage_name_id_service, + name_id_format=name_id_format, + signature=signature, + extensions=extensions, + key_descriptor=key_descriptor, + organization=organization, + contact_person=contact_person, + id=id, + valid_until=valid_until, + cache_duration=cache_duration, + protocol_support_enumeration=protocol_support_enumeration, + error_url=error_url, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.assertion_consumer_service=assertion_consumer_service or [] + self.attribute_consuming_service=attribute_consuming_service or [] + self.authn_requests_signed=authn_requests_signed + self.want_assertions_signed=want_assertions_signed + +def spsso_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SPSSODescriptorType, xml_string) + +class SPSSODescriptor(SPSSODescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:SPSSODescriptor element """ + + c_tag = 'SPSSODescriptor' + c_namespace = NAMESPACE + c_children = SPSSODescriptorType.c_children.copy() + c_attributes = SPSSODescriptorType.c_attributes.copy() + c_child_order = SPSSODescriptorType.c_child_order[:] + +def spsso_descriptor_from_string(xml_string): + return saml2.create_class_from_xml_string(SPSSODescriptor, xml_string) + +class EntityDescriptorType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:EntityDescriptorType element """ + + c_tag = 'EntityDescriptorType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Extensions'] = ('extensions', Extensions) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}RoleDescriptor'] = ('role_descriptor', [RoleDescriptor]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}IDPSSODescriptor'] = ('idpsso_descriptor', [IDPSSODescriptor]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}SPSSODescriptor'] = ('spsso_descriptor', [SPSSODescriptor]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AuthnAuthorityDescriptor'] = ('authn_authority_descriptor', [AuthnAuthorityDescriptor]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AttributeAuthorityDescriptor'] = ('attribute_authority_descriptor', [AttributeAuthorityDescriptor]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}PDPDescriptor'] = ('pdp_descriptor', [PDPDescriptor]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AffiliationDescriptor'] = ('affiliation_descriptor', [AffiliationDescriptor]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Organization'] = ('organization', [Organization]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}ContactPerson'] = ('contact_person', [ContactPerson]) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}AdditionalMetadataLocation'] = ('additional_metadata_location', [AdditionalMetadataLocation]) + c_attributes['entityID'] = ('entity_id', 'entityIDType', True) + c_attributes['validUntil'] = ('valid_until', 'dateTime', False) + c_attributes['cacheDuration'] = ('cache_duration', 'duration', False) + c_attributes['ID'] = ('id', 'ID', False) + c_child_order.extend(['signature', 'extensions', 'role_descriptor', 'idpsso_descriptor', 'spsso_descriptor', 'authn_authority_descriptor', 'attribute_authority_descriptor', 'pdp_descriptor', 'affiliation_descriptor', 'organization', 'contact_person', 'additional_metadata_location']) + + def __init__(self, + signature=None, + extensions=None, + role_descriptor=None, + idpsso_descriptor=None, + spsso_descriptor=None, + authn_authority_descriptor=None, + attribute_authority_descriptor=None, + pdp_descriptor=None, + affiliation_descriptor=None, + organization=None, + contact_person=None, + additional_metadata_location=None, + entity_id=None, + valid_until=None, + cache_duration=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.signature=signature + self.extensions=extensions + self.role_descriptor=role_descriptor or [] + self.idpsso_descriptor=idpsso_descriptor or [] + self.spsso_descriptor=spsso_descriptor or [] + self.authn_authority_descriptor=authn_authority_descriptor or [] + self.attribute_authority_descriptor=attribute_authority_descriptor or [] + self.pdp_descriptor=pdp_descriptor or [] + self.affiliation_descriptor=affiliation_descriptor or [] + self.organization=organization or [] + self.contact_person=contact_person or [] + self.additional_metadata_location=additional_metadata_location or [] + self.entity_id=entity_id + self.valid_until=valid_until + self.cache_duration=cache_duration + self.id=id + +def entity_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EntityDescriptorType, xml_string) + +class EntityDescriptor(EntityDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:EntityDescriptor element """ c_tag = 'EntityDescriptor' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['entityID'] = 'entity_id' - c_attributes['ID'] = 'id' - c_attributes['validUntil'] = 'valid_until' - c_attributes['cacheDuration'] = 'cache_duration' - c_required_attributes = ["entity_id"] - c_children['{%s}Signature' % DS_NAMESPACE] = ('signature', ds.Signature) - c_children['{%s}Extensions' % NAMESPACE] = ('extensions', Extensions) - c_children['{%s}RoleDescriptor' % NAMESPACE] = ( - 'role_descriptor', [RoleDescriptor]) - c_children['{%s}IDPSSODescriptor' % NAMESPACE] = ( - 'idp_sso_descriptor', [IDPSSODescriptor]) - c_children['{%s}SPSSODescriptor' % NAMESPACE] = ( - 'sp_sso_descriptor', [SPSSODescriptor]) - c_children['{%s}Organization' % NAMESPACE] = ( - 'organization', Organization) - c_children['{%s}ContactPerson' % NAMESPACE] = ( - 'contact_person', [ContactPerson]) - c_children['{%s}AdditionalMetadataLocation' % NAMESPACE] = ( - 'additional_metadata_location', [AdditionalMetadataLocation]) - c_children['{%s}AttributeAuthorityDescriptor' % NAMESPACE] = ( - 'attribute_authority_descriptor', - [AttributeAuthorityDescriptor]) - c_children['{%s}AffiliationDescriptor' % NAMESPACE] = ( - 'affiliation_descriptor', [AffiliationDescriptor]) - c_child_order = ['signature', 'extensions', 'role_descriptor', - 'idp_sso_descriptor', 'sp_sso_descriptor', 'organization', - 'contact_person', 'additional_metadata_location', - 'attribute_authority_descriptor', - 'affiliation_descriptor'] + c_children = EntityDescriptorType.c_children.copy() + c_attributes = EntityDescriptorType.c_attributes.copy() + c_child_order = EntityDescriptorType.c_child_order[:] - def __init__(self, entity_id=None, id=None, valid_until=None, - cache_duration=None, signature=None, extensions=None, - role_descriptor=None, idp_sso_descriptor=None, - sp_sso_descriptor=None, organization=None, - contact_person=None, additional_metadata_location=None, - attribute_authority_descriptor=None, - affiliation_descriptor=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for EntityDescriptor - - :param entity_id: entityID attribute - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param role_descriptor: RoleDescriptor elements - :param idp_sso_descriptor: IDPSSODescriptor elements - :param sp_sso_descriptor: SPSSODescriptor elements - :param organization: Organization element - :param contact_person: ContactPerson elements - :param additional_metadata_location: AdditionalMetadataLocation elements - :param affiliation_descriptor: - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.entity_id = entity_id - self.id = id - self.valid_until = valid_until - self.cache_duration = cache_duration - self.signature = signature - self.extensions = extensions - self.role_descriptor = role_descriptor or [] - self.idp_sso_descriptor = idp_sso_descriptor or [] - self.sp_sso_descriptor = sp_sso_descriptor or [] - self.organization = organization - self.contact_person = contact_person or [] - self.additional_metadata_location = additional_metadata_location or [] - self.attribute_authority_descriptor = \ - attribute_authority_descriptor or [] - self.affiliation_descriptor = affiliation_descriptor or [] - def entity_descriptor_from_string(xml_string): - """ Create EntityDescriptor instance from an XML string """ - return create_class_from_xml_string(EntityDescriptor, xml_string) + return saml2.create_class_from_xml_string(EntityDescriptor, xml_string) +#.................. +# ['EntitiesDescriptor', 'EntitiesDescriptorType'] +class EntitiesDescriptorType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:metadata:EntitiesDescriptorType element """ -class EntitiesDescriptor(SamlBase): - """The md:EntitiesDescriptor element""" - - c_tag = 'EntitiesDescriptor' + c_tag = 'EntitiesDescriptorType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['name'] = 'name' - c_attributes['ID'] = 'id' - c_attributes['validUntil'] = 'valid_until' - c_attributes['cacheDuration'] = 'cache_duration' - c_children['{%s}Signature' % DS_NAMESPACE] = ('signature', ds.Signature) - c_children['{%s}Extensions' % NAMESPACE] = ('extensions', Extensions) - c_children['{%s}EntityDescriptor' % NAMESPACE] = ( - 'entity_descriptor', [EntityDescriptor]) - # Entities desciption further down - c_child_order = ['signature', 'extensions', 'entity_descriptor', - 'entities_descriptor'] - c_required_child = ["entity_descriptor"] - - def __init__(self, name=None, id=None, valid_until=None, - cache_duration=None, signature=None, extensions=None, - entity_descriptor=None, entities_descriptor=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for EntitiesDescriptor + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}Extensions'] = ('extensions', Extensions) + c_children['{urn:oasis:names:tc:SAML:2.0:metadata}EntityDescriptor'] = ('entity_descriptor', [EntityDescriptor]) + c_attributes['validUntil'] = ('valid_until', 'dateTime', False) + c_attributes['cacheDuration'] = ('cache_duration', 'duration', False) + c_attributes['ID'] = ('id', 'ID', False) + c_attributes['Name'] = ('name', 'string', False) + c_child_order.extend(['signature', 'extensions', 'entity_descriptor', 'entities_descriptor']) - :param name: name attribute - :param id: ID attribute - :param valid_until: validUntil attribute - :param cache_duration: cacheDuration attribute - :param signature: ds:Signature element - :param extensions: Extensions element - :param entity_descriptor: EntityDescriptor elements - :param entities_descriptor: EntitiesDescriptor elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.name = name - self.id = id - self.valid_until = valid_until - self.cache_duration = cache_duration - self.signature = signature - self.extensions = extensions - self.entity_descriptor = entity_descriptor or [] - self.entities_descriptor = entities_descriptor or [] + def __init__(self, + signature=None, + extensions=None, + entity_descriptor=None, + entities_descriptor=None, + valid_until=None, + cache_duration=None, + id=None, + name=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.signature=signature + self.extensions=extensions + self.entity_descriptor=entity_descriptor or [] + self.entities_descriptor=entities_descriptor or [] + self.valid_until=valid_until + self.cache_duration=cache_duration + self.id=id + self.name=name + +def entities_descriptor_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EntitiesDescriptorType, xml_string) + +class EntitiesDescriptor(EntitiesDescriptorType): + """The urn:oasis:names:tc:SAML:2.0:metadata:EntitiesDescriptor element """ + + c_tag = 'EntitiesDescriptor' + c_namespace = NAMESPACE + c_children = EntitiesDescriptorType.c_children.copy() + c_attributes = EntitiesDescriptorType.c_attributes.copy() + c_child_order = EntitiesDescriptorType.c_child_order[:] -EntitiesDescriptor.c_children['{%s}EntitiesDescriptor' % NAMESPACE] = ( - 'entities_descriptor', [EntitiesDescriptor]) - def entities_descriptor_from_string(xml_string): - """ Create EntitiesDescriptor instance from an XML string """ - return create_class_from_xml_string(EntitiesDescriptor, xml_string) + return saml2.create_class_from_xml_string(EntitiesDescriptor, xml_string) -# --------------------------------------------------------------------------- - -IDPDISC = "urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol" - -class DiscoveryResponse(IndexedEndpoint): - """The idpdisc:DiscoveryResponse element""" - c_tag = 'DiscoveryResponse' - c_namespace = IDPDISC - -def discovery_response_from_string(xml_string): - """ Create DiscoveryResponse instance from an XML string """ - return create_class_from_xml_string(DiscoveryResponse, xml_string) - -# --------------------------------------------------------------------------- +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +EntitiesDescriptorType.c_children['{urn:oasis:names:tc:SAML:2.0:metadata}EntitiesDescriptor'] = ('entities_descriptor', [EntitiesDescriptor]) +EntitiesDescriptor.c_children['{urn:oasis:names:tc:SAML:2.0:metadata}EntitiesDescriptor'] = ('entities_descriptor', [EntitiesDescriptor]) +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ELEMENT_FROM_STRING = { - DiscoveryResponse.c_tag: discovery_response_from_string, + entityIDType.c_tag: entity_id_type_from_string, + localizedNameType.c_tag: localized_name_type_from_string, + localizedURIType.c_tag: localized_uri_type_from_string, Extensions.c_tag: extensions_from_string, - LocalizedName.c_tag: localized_name_from_string, - LocalizedURI.c_tag: localized_uri_from_string, + ExtensionsType.c_tag: extensions_type_from_string, + EndpointType.c_tag: endpoint_type_from_string, + IndexedEndpointType.c_tag: indexed_endpoint_type_from_string, + EntitiesDescriptor.c_tag: entities_descriptor_from_string, + EntitiesDescriptorType.c_tag: entities_descriptor_type_from_string, + EntityDescriptor.c_tag: entity_descriptor_from_string, + EntityDescriptorType.c_tag: entity_descriptor_type_from_string, + Organization.c_tag: organization_from_string, + OrganizationType.c_tag: organization_type_from_string, OrganizationName.c_tag: organization_name_from_string, OrganizationDisplayName.c_tag: organization_display_name_from_string, OrganizationURL.c_tag: organization_url_from_string, - Organization.c_tag: organization_from_string, - Endpoint.c_tag: endpoint_from_string, - IndexedEndpoint.c_tag: indexed_endpoint_from_string, - AuthzService.c_tag: authz_service_from_string, - AssertionIDRequestService.c_tag: assertion_id_request_service_from_string, - AuthnQueryService.c_tag: authn_query_service_from_string, + ContactPerson.c_tag: contact_person_from_string, + ContactType.c_tag: contact_type_from_string, Company.c_tag: company_from_string, GivenName.c_tag: given_name_from_string, SurName.c_tag: sur_name_from_string, EmailAddress.c_tag: email_address_from_string, TelephoneNumber.c_tag: telephone_number_from_string, - ContactPerson.c_tag: contact_person_from_string, + ContactTypeType.c_tag: contact_type_type_from_string, AdditionalMetadataLocation.c_tag: additional_metadata_location_from_string, - KeySize.c_tag: key_size_from_string, - OAEPparams.c_tag: oae_pparams_from_string, - EncryptionMethod.c_tag: encryption_method_from_string, - KeyDescriptor.c_tag: key_descriptor_from_string, + AdditionalMetadataLocationType.c_tag: additional_metadata_location_type_from_string, RoleDescriptor.c_tag: role_descriptor_from_string, + RoleDescriptorType.c_tag: role_descriptor_type_from_string, + anyURIListType.c_tag: any_uri_list_type_from_string, + KeyDescriptor.c_tag: key_descriptor_from_string, + KeyDescriptorType.c_tag: key_descriptor_type_from_string, + KeyTypes.c_tag: key_types_from_string, + EncryptionMethod.c_tag: encryption_method_from_string, + SSODescriptorType.c_tag: sso_descriptor_type_from_string, ArtifactResolutionService.c_tag: artifact_resolution_service_from_string, - AssertionConsumerService.c_tag: assertion_consumer_service_from_string, SingleLogoutService.c_tag: single_logout_service_from_string, ManageNameIDService.c_tag: manage_name_id_service_from_string, NameIDFormat.c_tag: name_id_format_from_string, - EntityIDType.c_tag: entity_id_type_from_string, - AffiliateMember.c_tag: affiliate_member_from_string, - PDPDescriptor.c_tag: pdp_descriptor_from_string, - SSODescriptor.c_tag: sso_descriptor_from_string, + IDPSSODescriptor.c_tag: idpsso_descriptor_from_string, + IDPSSODescriptorType.c_tag: idpsso_descriptor_type_from_string, SingleSignOnService.c_tag: single_sign_on_service_from_string, NameIDMappingService.c_tag: name_id_mapping_service_from_string, AssertionIDRequestService.c_tag: assertion_id_request_service_from_string, - AttributeService.c_tag: attribute_service_from_string, AttributeProfile.c_tag: attribute_profile_from_string, - IDPSSODescriptor.c_tag: idpsso_descriptor_from_string, - RequestedAttribute.c_tag: requested_attribute_from_string, + SPSSODescriptor.c_tag: spsso_descriptor_from_string, + SPSSODescriptorType.c_tag: spsso_descriptor_type_from_string, + AssertionConsumerService.c_tag: assertion_consumer_service_from_string, + AttributeConsumingService.c_tag: attribute_consuming_service_from_string, + AttributeConsumingServiceType.c_tag: attribute_consuming_service_type_from_string, ServiceName.c_tag: service_name_from_string, ServiceDescription.c_tag: service_description_from_string, - AttributeConsumingService.c_tag: attribute_consuming_service_from_string, - SPSSODescriptor.c_tag: spsso_descriptor_from_string, - AttributeAuthorityDescriptor.c_tag: attribute_authority_descriptor_from_string, - AffiliationDescriptor.c_tag: affiliation_descriptor_from_string, + RequestedAttribute.c_tag: requested_attribute_from_string, + RequestedAttributeType.c_tag: requested_attribute_type_from_string, AuthnAuthorityDescriptor.c_tag: authn_authority_descriptor_from_string, - EntityDescriptor.c_tag: entity_descriptor_from_string, - EntitiesDescriptor.c_tag: entities_descriptor_from_string, + AuthnAuthorityDescriptorType.c_tag: authn_authority_descriptor_type_from_string, + AuthnQueryService.c_tag: authn_query_service_from_string, + PDPDescriptor.c_tag: pdp_descriptor_from_string, + PDPDescriptorType.c_tag: pdp_descriptor_type_from_string, + AuthzService.c_tag: authz_service_from_string, + AttributeAuthorityDescriptor.c_tag: attribute_authority_descriptor_from_string, + AttributeAuthorityDescriptorType.c_tag: attribute_authority_descriptor_type_from_string, + AttributeService.c_tag: attribute_service_from_string, + AffiliationDescriptor.c_tag: affiliation_descriptor_from_string, + AffiliationDescriptorType.c_tag: affiliation_descriptor_type_from_string, + AffiliateMember.c_tag: affiliate_member_from_string, } +ELEMENT_BY_TAG = { + 'entityIDType': entityIDType, + 'localizedNameType': localizedNameType, + 'localizedURIType': localizedURIType, + 'Extensions': Extensions, + 'ExtensionsType': ExtensionsType, + 'EndpointType': EndpointType, + 'IndexedEndpointType': IndexedEndpointType, + 'EntitiesDescriptor': EntitiesDescriptor, + 'EntitiesDescriptorType': EntitiesDescriptorType, + 'EntityDescriptor': EntityDescriptor, + 'EntityDescriptorType': EntityDescriptorType, + 'Organization': Organization, + 'OrganizationType': OrganizationType, + 'OrganizationName': OrganizationName, + 'OrganizationDisplayName': OrganizationDisplayName, + 'OrganizationURL': OrganizationURL, + 'ContactPerson': ContactPerson, + 'ContactType': ContactType, + 'Company': Company, + 'GivenName': GivenName, + 'SurName': SurName, + 'EmailAddress': EmailAddress, + 'TelephoneNumber': TelephoneNumber, + 'ContactTypeType': ContactTypeType, + 'AdditionalMetadataLocation': AdditionalMetadataLocation, + 'AdditionalMetadataLocationType': AdditionalMetadataLocationType, + 'RoleDescriptor': RoleDescriptor, + 'RoleDescriptorType': RoleDescriptorType, + 'anyURIListType': anyURIListType, + 'KeyDescriptor': KeyDescriptor, + 'KeyDescriptorType': KeyDescriptorType, + 'KeyTypes': KeyTypes, + 'EncryptionMethod': EncryptionMethod, + 'SSODescriptorType': SSODescriptorType, + 'ArtifactResolutionService': ArtifactResolutionService, + 'SingleLogoutService': SingleLogoutService, + 'ManageNameIDService': ManageNameIDService, + 'NameIDFormat': NameIDFormat, + 'IDPSSODescriptor': IDPSSODescriptor, + 'IDPSSODescriptorType': IDPSSODescriptorType, + 'SingleSignOnService': SingleSignOnService, + 'NameIDMappingService': NameIDMappingService, + 'AssertionIDRequestService': AssertionIDRequestService, + 'AttributeProfile': AttributeProfile, + 'SPSSODescriptor': SPSSODescriptor, + 'SPSSODescriptorType': SPSSODescriptorType, + 'AssertionConsumerService': AssertionConsumerService, + 'AttributeConsumingService': AttributeConsumingService, + 'AttributeConsumingServiceType': AttributeConsumingServiceType, + 'ServiceName': ServiceName, + 'ServiceDescription': ServiceDescription, + 'RequestedAttribute': RequestedAttribute, + 'RequestedAttributeType': RequestedAttributeType, + 'AuthnAuthorityDescriptor': AuthnAuthorityDescriptor, + 'AuthnAuthorityDescriptorType': AuthnAuthorityDescriptorType, + 'AuthnQueryService': AuthnQueryService, + 'PDPDescriptor': PDPDescriptor, + 'PDPDescriptorType': PDPDescriptorType, + 'AuthzService': AuthzService, + 'AttributeAuthorityDescriptor': AttributeAuthorityDescriptor, + 'AttributeAuthorityDescriptorType': AttributeAuthorityDescriptorType, + 'AttributeService': AttributeService, + 'AffiliationDescriptor': AffiliationDescriptor, + 'AffiliationDescriptorType': AffiliationDescriptorType, + 'AffiliateMember': AffiliateMember, +} + +def factory(tag, **kwargs): + return ELEMENT_BY_TAG[tag](**kwargs) + diff --git a/src/saml2/metadata.py b/src/saml2/metadata.py index 2f00965..9b42988 100644 --- a/src/saml2/metadata.py +++ b/src/saml2/metadata.py @@ -88,7 +88,7 @@ class MetaData(object): :param entity_descriptor: A EntityDescriptor instance """ try: - ssd = entity_descriptor.sp_sso_descriptor + ssd = entity_descriptor.spsso_descriptor except AttributeError: return @@ -141,7 +141,7 @@ class MetaData(object): :param entity_descriptor: A EntityDescriptor instance """ try: - isd = entity_descriptor.idp_sso_descriptor + isd = entity_descriptor.idpsso_descriptor except AttributeError: return @@ -280,7 +280,7 @@ class MetaData(object): except AttributeError: pass try: - entity["contact"] = entity_descriptor.contact + entity["contact_person"] = entity_descriptor.contact_person except AttributeError: pass @@ -394,23 +394,26 @@ class MetaData(object): :param entityid: The Entity ID :return: A name """ + name = "" + try: - org = self.entity[entity_id]["organization"] - try: - names = org.organization_display_name - except KeyError: + for org in self.entity[entity_id]["organization"]: try: - names = org.organization_name - except KeyError: - try: - names = org.organization_url - except KeyError: - names = None - if names: - name = names[0].text + name = org.organization_display_name[0] + except IndexError: + try: + name = org.organization_name[0] + except IndexError: + try: + name = org.organization_url[0] + except IndexError: + pass + + if name: + name = name.text except KeyError: - name = "" - + pass + return name @keep_updated diff --git a/src/saml2/saml.py b/src/saml2/saml.py index 08dc72d..3216cbc 100644 --- a/src/saml2/saml.py +++ b/src/saml2/saml.py @@ -1,37 +1,15 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright (C) 2007 SIOS Technology, Inc. -# 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. +#!/usr/bin/env python -"""Contains classes representing Saml elements. +# +# Generated Thu Jul 15 21:01:26 2010 by parse_xsd.py version 0.3. +# - Module objective: provide data classes for Saml constructs. These - classes hide the XML-ness of Saml and provide a set of native Python - classes to interact with. - - Conversions to and from XML should only be necessary when the Saml classes - "touch the wire" and are sent over HTTP. For this reason this module - provides methods and functions to convert Saml classes to and from strings. -""" - -import xmldsig as ds -import xmlenc import saml2 from saml2 import SamlBase +import xmldsig as ds +import xmlenc as xenc + NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' @@ -55,7 +33,10 @@ NAMEID_FORMAT_ENTITY = ( PROFILE_ATTRIBUTE_BASIC = ( "urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic") -URN_PASSWORD = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password" +AUTHN_PASSWORD = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password" +AUTHN_PASSWORD_PROTECTED = \ + "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" + NAME_FORMAT_UNSPECIFIED = ( "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified") NAME_FORMAT_URI = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri" @@ -68,781 +49,428 @@ DECISION_TYPE_INDETERMINATE = "Indeterminate" CONSENT_UNSPECIFIED = "urn:oasis:names:tc:SAML:2.0:consent:unspecified" -# --------------------------------------------------------------------------- -# BaseID -# --------------------------------------------------------------------------- -class BaseID(SamlBase): - """ The saml:BaseID element """ +class BaseIDAbstractType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element """ - c_tag = 'BaseID' + c_tag = 'BaseIDAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['NameQualifier'] = 'name_qualifier' - c_attributes['SPNameQualifier'] = 'sp_name_qualifier' + c_child_order = SamlBase.c_child_order[:] + c_attributes['NameQualifier'] = ('name_qualifier', 'string', False) + c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) - def __init__(self, name_qualifier=None, sp_name_qualifier=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for BaseID, an extension point that allows applications - to add new kinds of identifiers. + def __init__(self, + name_qualifier=None, + sp_name_qualifier=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.name_qualifier=name_qualifier + self.sp_name_qualifier=sp_name_qualifier - :param name_qualifier: NameQualifier attribute; The security or - administrative domain that qualifies the identifier. - :param sp_name_qualifier: SPNameQualifier attribute; Further qualifies - an identifier with the name of a service provider or affiliation - of providers. - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs. - """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.name_qualifier = name_qualifier - self.sp_name_qualifier = sp_name_qualifier - -def base_id_from_string(xml_string): - """ Create BaseID instance from an XML string """ - return saml2.create_class_from_xml_string(BaseID, xml_string) +def base_id_abstract_type_from_string(xml_string): + return saml2.create_class_from_xml_string(BaseIDAbstractType, xml_string) -# --------------------------------------------------------------------------- -# NameID -# --------------------------------------------------------------------------- +class NameIDType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element """ -class NameID(BaseID): - """The saml:NameID element""" - - c_tag = 'NameID' + c_tag = 'NameIDType' c_namespace = NAMESPACE - c_children = BaseID.c_children.copy() - c_attributes = BaseID.c_attributes.copy() - c_attributes['Format'] = 'format' - c_attributes['SPProvidedID'] = 'sp_provided_id' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['NameQualifier'] = ('name_qualifier', 'string', False) + c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) + c_attributes['Format'] = ('format', 'anyURI', False) + c_attributes['SPProvidedID'] = ('sp_provided_id', 'string', False) - def __init__(self, name_qualifier=None, sp_name_qualifier=None, - format=None, sp_provided_id=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for NameID + def __init__(self, + name_qualifier=None, + sp_name_qualifier=None, + format=None, + sp_provided_id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.name_qualifier=name_qualifier + self.sp_name_qualifier=sp_name_qualifier + self.format=format + self.sp_provided_id=sp_provided_id - :param format: Format attribute; A URI reference representing the - classification of string-based identifier information. - :param sp_provided_id: SPProvidedID attribute; A name identifier - established by a service provider or affiliation of providers - for the entity, if different from the primary name identifier - given in the content of the element. - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +def name_id_type_from_string(xml_string): + return saml2.create_class_from_xml_string(NameIDType, xml_string) - BaseID.__init__(self, name_qualifier, sp_name_qualifier, text, - extension_elements, extension_attributes) - - self.format = format - self.sp_provided_id = sp_provided_id +class EncryptedElementType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element """ -def name_id_from_string(xml_string): - """ Create NameID instance from an XML string """ - return saml2.create_class_from_xml_string(NameID, xml_string) + c_tag = 'EncryptedElementType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = ('encrypted_data', xenc.EncryptedData) + c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = ('encrypted_key', [xenc.EncryptedKey]) + c_child_order.extend(['encrypted_data', 'encrypted_key']) -# --------------------------------------------------------------------------- -# EncryptedID -# --------------------------------------------------------------------------- + def __init__(self, + encrypted_data=None, + encrypted_key=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.encrypted_data=encrypted_data + self.encrypted_key=encrypted_key or [] + +def encrypted_element_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptedElementType, xml_string) + +class EncryptedID(EncryptedElementType): + """The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element """ -class EncryptedID(SamlBase): - """The saml:EncryptedID element""" c_tag = 'EncryptedID' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - - # TODO: This is just a skelton yet. + c_children = EncryptedElementType.c_children.copy() + c_attributes = EncryptedElementType.c_attributes.copy() + c_child_order = EncryptedElementType.c_child_order[:] def encrypted_id_from_string(xml_string): - """ Create EncryptedID instance from an XML string """ return saml2.create_class_from_xml_string(EncryptedID, xml_string) -# --------------------------------------------------------------------------- -# Issuer -# --------------------------------------------------------------------------- - -class Issuer(NameID): - """The saml:Issuer element""" +class Issuer(NameIDType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element """ c_tag = 'Issuer' - c_children = NameID.c_children.copy() - c_attributes = NameID.c_attributes.copy() + c_namespace = NAMESPACE + c_children = NameIDType.c_children.copy() + c_attributes = NameIDType.c_attributes.copy() + c_child_order = NameIDType.c_child_order[:] def issuer_from_string(xml_string): - """ Create Issuer instance from an XML string """ return saml2.create_class_from_xml_string(Issuer, xml_string) - -# --------------------------------------------------------------------------- -# AssertionIDRef -# --------------------------------------------------------------------------- - class AssertionIDRef(SamlBase): - """The saml:AssertionIDRef element makes a reference to a SAML assertion - by its unique identifier.""" + """The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element """ + c_tag = 'AssertionIDRef' c_namespace = NAMESPACE + c_value_type = 'NCName' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def assertion_id_ref_from_string(xml_string): - """ Create AssertionIDRef instance from an XML string """ return saml2.create_class_from_xml_string(AssertionIDRef, xml_string) -# --------------------------------------------------------------------------- -# AssertionURIRef -# --------------------------------------------------------------------------- - class AssertionURIRef(SamlBase): - """The saml:AssertionURIRef element makes a reference to a SAML assertion - by URI reference.""" + """The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element """ + c_tag = 'AssertionURIRef' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def assertion_uri_ref_from_string(xml_string): - """ Create AssertionURIRef instance from an XML string """ return saml2.create_class_from_xml_string(AssertionURIRef, xml_string) -# --------------------------------------------------------------------------- -# EncryptedElement -# --------------------------------------------------------------------------- +class SubjectConfirmationDataType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element """ -class EncryptedElement(SamlBase): - - c_tag = 'EncryptedElement' + c_tag = 'SubjectConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['NotBefore'] = ('not_before', 'dateTime', False) + c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) + c_attributes['Recipient'] = ('recipient', 'anyURI', False) + c_attributes['InResponseTo'] = ('in_response_to', 'NCName', False) + c_attributes['Address'] = ('address', 'string', False) - c_children['{%s}EncryptedData' % xmlenc.NAMESPACE] = ( - 'encrypted_data', xmlenc.EncryptedData) - c_children['{%s}EncryptedKey' % xmlenc.NAMESPACE] = ( - 'encrypted_key', xmlenc.EncryptedKey) - c_child_order = ["encrypted_data", "encrypted_key", "encrypted_id"] - - def __init__(self, encrypted_data=None, encrypted_key=None, - encrypted_id=None, - text=None, - extension_elements=None, - extension_attributes=None): + def __init__(self, + not_before=None, + not_on_or_after=None, + recipient=None, + in_response_to=None, + address=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.not_before=not_before + self.not_on_or_after=not_on_or_after + self.recipient=recipient + self.in_response_to=in_response_to + self.address=address - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.encrypted_data = encrypted_data - self.encrypted_key = encrypted_key - self.encrypted_id = encrypted_id +def subject_confirmation_data_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectConfirmationDataType, xml_string) -def encrypted_element_from_string(xml_string): - """ Create EncryptedElement instance from an XML string """ - return saml2.create_class_from_xml_string(EncryptedElement, xml_string) +class KeyInfoConfirmationDataType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element """ -# --------------------------------------------------------------------------- -# EncryptedID -# --------------------------------------------------------------------------- - -class EncryptedID(EncryptedElement): - c_tag = 'EncryptedID' - c_namespace = NAMESPACE - c_children = EncryptedElement.c_children.copy() - c_attributes = EncryptedElement.c_attributes.copy() - -def encrypted_id_from_string(xml_string): - """ Create EncryptedID instance from an XML string """ - return saml2.create_class_from_xml_string(EncryptedID, xml_string) - - -EncryptedElement.c_children['{%s}EncryptedID' % NAMESPACE] = ( - 'encrypted_id', EncryptedID) - -# --------------------------------------------------------------------------- -# EncryptedAssertion -# --------------------------------------------------------------------------- - -class EncryptedAssertion(EncryptedElement): - """The saml:EncryptedAssertion element represents an assertion in - encrypted fashion, as defined by the XML Encryption Syntax and - Processing specification""" - - c_tag = 'EncryptedAssertion' - c_namespace = NAMESPACE - c_children = EncryptedElement.c_children.copy() - c_attributes = EncryptedElement.c_attributes.copy() - - # TODO: This is just a skelton yet. - -def encrypted_assertion_from_string(xml_string): - """ Create EncryptedAssertion instance from an XML string """ - return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) - -# =========================================================================== -# SubjectConfirmationData -# --------------------------------------------------------------------------- - -class SubjectConfirmationData(SamlBase): - """The saml:SubjectConfirmationData element has the - SubjectConfirmationDataType complex type. It specifies additional data - that allows the subject to be confirmed or constrains the circumstances - under which the act of subject confirmation can take place""" - - c_tag = 'SubjectConfirmationData' + c_tag = 'KeyInfoConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['NotBefore'] = 'not_before' - c_attributes['NotOnOrAfter'] = 'not_on_or_after' - c_attributes['Recipient'] = 'recipient' - c_attributes['InResponseTo'] = 'in_response_to' - c_attributes['Address'] = 'address' - - def __init__(self, not_before=None, not_on_or_after=None, recipient=None, - in_response_to=None, address=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for SubjectConfirmationData + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', [ds.KeyInfo]) + c_child_order.extend(['key_info']) - :param not_before: NotBefore attribute; A time instant before which - the subject cannot be confirmed. - :param not_on_or_after: NotOnOrAfter attribute; A time instant at - which the subject can no longer be confirmed. - :param recipient: Recipient attribute; A URI specifying the entity or - location to which an attesting entity can present the assertion. - For example, this attribute might indicate that the assertion must - be delivered to a particular network endpoint in order to prevent - an intermediary from redirecting it someplace else. - :param in_response_to: InResponseTo attribute; The ID of a SAML - protocol message in response to which an attesting entity can - present the assertion. - :param address: Address attribute; The network address/location from - which an attesting entity can present the assertion. - :param text: The text data in this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ + def __init__(self, + key_info=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.key_info=key_info or [] - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.not_before = not_before - self.not_on_or_after = not_on_or_after - self.recipient = recipient - self.in_response_to = in_response_to - self.address = address +def key_info_confirmation_data_type_from_string(xml_string): + return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType, xml_string) -def subject_confirmation_data_from_string(xml_string): - """ Create SubjectConfirmationData instance from an XML string """ - return saml2.create_class_from_xml_string(SubjectConfirmationData, - xml_string) +class ConditionAbstractType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element """ -# --------------------------------------------------------------------------- -# KeyInfoConfirmationDataType -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -# SubjectConfirmation -# --------------------------------------------------------------------------- - -class SubjectConfirmation(SamlBase): - """The saml:SubjectConfirmation element provides the means for a relying - party to verify the correspondence of the subject of the assertion with - the party with whom the relying party is communicating.""" - - c_tag = 'SubjectConfirmation' + c_tag = 'ConditionAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['Method'] = 'method' - c_children['{%s}BaseID' % NAMESPACE] = ('base_id', BaseID) - c_children['{%s}NameID' % NAMESPACE] = ('name_id', NameID) - c_children['{%s}EncryptedID' % NAMESPACE] = ('encrypted_id', - EncryptedID) - c_children['{%s}SubjectConfirmationData' % NAMESPACE] = ( - 'subject_confirmation_data', SubjectConfirmationData) - c_child_order = ['base_id', 'name_id', 'encrypted_id', - 'subject_confirmation_data'] + c_child_order = SamlBase.c_child_order[:] - def __init__(self, method=None, base_id=None, name_id=None, - encrypted_id=None, - subject_confirmation_data=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for SubjectConfirmation - - :param method: Subject confirmation method - :param base_id: Method attribute - :param name_id: NameID element - :param subject_confirmation_data: SubjectConfirmationData element - :param text: The text data in this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.method = method - self.base_id = base_id - self.name_id = name_id - self.encrypted_id = encrypted_id - self.subject_confirmation_data = subject_confirmation_data - -def subject_confirmation_from_string(xml_string): - """ Create SubjectConfirmation instance from an XML string """ - return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) - -# --------------------------------------------------------------------------- -# Subject -# --------------------------------------------------------------------------- - -class Subject(SamlBase): - """The saml:Subject element""" - - c_tag = 'Subject' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_children['{%s}NameID' % NAMESPACE] = ('name_id', NameID) - c_children['{%s}SubjectConfirmation' % NAMESPACE] = ( - 'subject_confirmation', [SubjectConfirmation]) - c_child_order = ['name_id', 'subject_confirmation'] - - def __init__(self, name_id=None, subject_confirmation=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for SubjectConfirmation - - :param name_id: NameID element - :param subject_confirmation: SubjectConfirmation element - :param text: The text data in this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.name_id = name_id - self.subject_confirmation = subject_confirmation or [] - -def subject_from_string(xml_string): - """ Create Subject instance from an XML string """ - return saml2.create_class_from_xml_string(Subject, xml_string) - - -# =========================================================================== -# Condition -# --------------------------------------------------------------------------- - -class Condition(SamlBase): - """The saml:Condition element""" - - c_tag = 'Condition' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - -def condition_from_string(xml_string): - """ Create Condition instance from an XML string """ - return saml2.create_class_from_xml_string(Condition, xml_string) - - -# --------------------------------------------------------------------------- -# Audience -# --------------------------------------------------------------------------- +def condition_abstract_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ConditionAbstractType, xml_string) class Audience(SamlBase): - """The saml:Audience element, a URI reference that identifies an intended - audience.""" + """The urn:oasis:names:tc:SAML:2.0:assertion:Audience element """ c_tag = 'Audience' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def audience_from_string(xml_string): - """ Create Audience instance from an XML string """ return saml2.create_class_from_xml_string(Audience, xml_string) -# --------------------------------------------------------------------------- -# AudienceRestriction -# --------------------------------------------------------------------------- +class OneTimeUseType(ConditionAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element """ -class AudienceRestriction(Condition): - """The saml:AudienceRestriction element specifies that the assertion is - addressed to one or more specific audiences identified by - elements.""" - - c_tag = 'AudienceRestriction' + c_tag = 'OneTimeUseType' c_namespace = NAMESPACE - c_children = Condition.c_children.copy() - c_attributes = Condition.c_attributes.copy() - c_children['{%s}Audience' % NAMESPACE] = ('audience', Audience) + c_children = ConditionAbstractType.c_children.copy() + c_attributes = ConditionAbstractType.c_attributes.copy() + c_child_order = ConditionAbstractType.c_child_order[:] - def __init__(self, audience=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for AudienceRestriction +def one_time_use_type_from_string(xml_string): + return saml2.create_class_from_xml_string(OneTimeUseType, xml_string) - :param text: The text data in this element - :param audience: Audience elements - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +class ProxyRestrictionType(ConditionAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element """ - Condition.__init__(self, text, extension_elements, - extension_attributes) - self.audience = audience - -def audience_restriction_from_string(xml_string): - """ Create AudienceRestriction instance from an XML string """ - return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) - -# --------------------------------------------------------------------------- -# OneTimeUse -# --------------------------------------------------------------------------- - -class OneTimeUse(Condition): - """The saml:OneTimeUse element. In general, relying parties may choose to - retain assertions, or the information they contain in some other form, - for reuse. The condition element allows an authority to - indicate that the information in the assertion is likely to change very - soon and fresh information should be obtained for each use.""" - - c_tag = 'OneTimeUse' - c_children = Condition.c_children.copy() - c_attributes = Condition.c_attributes.copy() - -def one_time_use_from_string(xml_string): - """ Create OneTimeUse instance from an XML string """ - return saml2.create_class_from_xml_string(OneTimeUse, xml_string) - -# --------------------------------------------------------------------------- -# OneTimeUse -# --------------------------------------------------------------------------- - -class ProxyRestriction(Condition): - """The saml:ProxyRestriction element. Specifies limitations that the - asserting party imposes on relying parties that in turn wish to act as - asserting parties and issue subsequent assertions of their own on the basis - of the information contained in the original assertion.""" - - c_tag = 'ProxyRestriction' + c_tag = 'ProxyRestrictionType' c_namespace = NAMESPACE - c_children = Condition.c_children.copy() - c_attributes = Condition.c_attributes.copy() - c_attributes['Count'] = 'count' - c_children['{%s}Audience' % NAMESPACE] = ('audience', [Audience]) + c_children = ConditionAbstractType.c_children.copy() + c_attributes = ConditionAbstractType.c_attributes.copy() + c_child_order = ConditionAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) + c_attributes['Count'] = ('count', 'nonNegativeInteger', False) + c_child_order.extend(['audience']) - def __init__(self, count=None, audience=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for ProxyRestriction + def __init__(self, + audience=None, + count=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + ConditionAbstractType.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.audience=audience or [] + self.count=count - :param text: The text data in this element - :param count: Count attribute - :param audience: Audience elements - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +def proxy_restriction_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ProxyRestrictionType, xml_string) - Condition.__init__(self, extension_elements, extension_attributes, - text) - self.count = count - self.audience = audience or [] +class EncryptedAssertion(EncryptedElementType): + """The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element """ -def proxy_restriction_from_string(xml_string): - """ Create ProxyRestriction instance from an XML string """ - return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) - - -# --------------------------------------------------------------------------- -# Conditions -# --------------------------------------------------------------------------- - -class Conditions(SamlBase): - """The saml:Conditions element""" - - c_tag = 'Conditions' + c_tag = 'EncryptedAssertion' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['NotBefore'] = 'not_before' - c_attributes['NotOnOrAfter'] = 'not_on_or_after' - c_children['{%s}Condition' % NAMESPACE] = ('condition', [Condition]) - c_children['{%s}AudienceRestriction' % NAMESPACE] = ( - 'audience_restriction', [AudienceRestriction]) - c_children['{%s}OneTimeUse' % NAMESPACE] = ( - 'one_time_use', [OneTimeUse]) - c_children['{%s}ProxyRestriction' % NAMESPACE] = ( - 'proxy_restriction', [ProxyRestriction]) - c_child_order = ['condition', 'audience_restriction', 'one_time_use', - 'proxy_restriction'] + c_children = EncryptedElementType.c_children.copy() + c_attributes = EncryptedElementType.c_attributes.copy() + c_child_order = EncryptedElementType.c_child_order[:] - def __init__(self, not_before=None, not_on_or_after=None, - condition=None, audience_restriction=None, - one_time_use=None, proxy_restriction=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for ProxyRestriction +def encrypted_assertion_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) - :param not_before: NotBefore attribute; Specifies the earliest - time instant at which the assertion is valid. - :param not_on_or_after: NotOnOrAfter attribute; Specifies the - time instant at which the assertion has expired. - :param condition: Condition elements; A condition of a type - defined in an extension schema. - :param audience_restriction: AudienceRestriction elements; - Specifies that the assertion is addressed to a particular audience. - :param one_time_use: OneTimeUse elements; Specifies that the assertion - SHOULD be used immediately and MUST NOT be retained for future use. - :param proxy_restriction: ProxyRestriction elements; Specifies - limitations that the asserting party imposes on relying parties - that wish to subsequently act as asserting parties themselves and - issue assertions of their own on the basis of the information - contained in the original assertion. - :param text: The text data in this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +class StatementAbstractType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.not_before = not_before - self.not_on_or_after = not_on_or_after - self.condition = condition or [] - self.audience_restriction = audience_restriction or [] - self.one_time_use = one_time_use or [] - self.proxy_restriction = proxy_restriction or [] - -def conditions_from_string(xml_string): - """ Create Conditions instance from an XML string """ - return saml2.create_class_from_xml_string(Conditions, xml_string) - - -# --------------------------------------------------------------------------- -# Statement -# --------------------------------------------------------------------------- - -class Statement(SamlBase): - """The saml:Statement element is an extension point that allows other - assertion-based applications to reuse the SAML assertion framework.""" - - c_tag = 'Statement' + c_tag = 'StatementAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - -def statement_from_string(xml_string): - """ Create Statement instance from an XML string """ - return saml2.create_class_from_xml_string(Statement, xml_string) + c_child_order = SamlBase.c_child_order[:] -# --------------------------------------------------------------------------- -# SubjectLocality -# --------------------------------------------------------------------------- +def statement_abstract_type_from_string(xml_string): + return saml2.create_class_from_xml_string(StatementAbstractType, xml_string) -class SubjectLocality(SamlBase): - """The saml:SubjectLocality element""" +class SubjectLocalityType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element """ - c_tag = 'SubjectLocality' + c_tag = 'SubjectLocalityType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['Address'] = 'address' - c_attributes['DNSName'] = 'dns_name' + c_child_order = SamlBase.c_child_order[:] + c_attributes['Address'] = ('address', 'string', False) + c_attributes['DNSName'] = ('dns_name', 'string', False) - def __init__(self, address=None, dns_name=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for SubjectLocality + def __init__(self, + address=None, + dns_name=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.address=address + self.dns_name=dns_name - :param address: Address attribute - :param dns_name: DNSName attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.address = address - self.dns_name = dns_name - -def subject_locality_from_string(xml_string): - """ Create SubjectLocality instance from an XML string """ - return saml2.create_class_from_xml_string(SubjectLocality, xml_string) - -# --------------------------------------------------------------------------- -# AuthnContextClassRef -# --------------------------------------------------------------------------- +def subject_locality_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectLocalityType, xml_string) class AuthnContextClassRef(SamlBase): - """The saml:AuthnContextClassRef element""" + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element """ c_tag = 'AuthnContextClassRef' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def authn_context_class_ref_from_string(xml_string): - """ Create AuthnContextClassRef instance from an XML string """ return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) - class AuthnContextDeclRef(SamlBase): - """The saml:AuthnContextDeclRef element""" + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element """ c_tag = 'AuthnContextDeclRef' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def authn_context_decl_ref_from_string(xml_string): - """ Create AuthnContextDeclRef instance from an XML string """ return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) - class AuthnContextDecl(SamlBase): - """The saml:AuthnContextDecl element""" + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element """ c_tag = 'AuthnContextDecl' c_namespace = NAMESPACE + c_value_type = 'anyType' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def authn_context_decl_from_string(xml_string): - """ Create AuthnContextDecl instance from an XML string """ return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) - class AuthenticatingAuthority(SamlBase): - """The saml:AuthenticatingAuthority element""" + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element """ c_tag = 'AuthenticatingAuthority' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def authenticating_authority_from_string(xml_string): - """ Create AuthenticatingAuthority instance from an XML string """ - return saml2.create_class_from_xml_string(AuthenticatingAuthority, - xml_string) + return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) +class DecisionType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element """ -class AuthnContext(SamlBase): - """The saml:AuthnContext element""" + c_tag = 'DecisionType' + c_namespace = NAMESPACE + c_value_type = {'base': 'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']} + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - c_tag = 'AuthnContext' +def decision_type_from_string(xml_string): + return saml2.create_class_from_xml_string(DecisionType, xml_string) + +class ActionType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element """ + + c_tag = 'ActionType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_children['{%s}AuthnContextClassRef' % NAMESPACE] = ( - 'authn_context_class_ref', AuthnContextClassRef) - c_children['{%s}AuthnContextDeclRef' % NAMESPACE] = ( - 'authn_context_decl_ref', AuthnContextDeclRef) - c_children['{%s}AuthnContextDecl' % NAMESPACE] = ( - 'authn_context_decl', AuthnContextDecl) - c_children['{%s}AuthenticatingAuthority' % NAMESPACE] = ( - 'authenticating_authority', [AuthenticatingAuthority]) - c_child_order = ['authn_context_class_ref', - 'authn_context_decl', 'authn_context_decl_ref', - 'authenticating_authority'] + c_child_order = SamlBase.c_child_order[:] + c_attributes['Namespace'] = ('namespace', 'anyURI', True) - def __init__(self, authn_context_class_ref=None, - authn_context_decl=None, authn_context_decl_ref=None, - authenticating_authority=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AuthnContext + def __init__(self, + namespace=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.namespace=namespace - Args: - :param authn_context_class_ref: AuthnContextClassRef element; - A URI reference identifying an authentication context class - that describes the authentication context declaration that follows. - :param authn_context_decl: AuthnContextDecl element - :param authn_context_decl_ref: AuthnContextDeclRef element; - Either an authentication context declaration provided by value, - or a URI reference that identifies such a declaration. - :param authenticating_authority: AuthenticatingAuthority element; - Zero or more unique identifiers of authentication authorities - that were involved in the authentication of the principal - (not including the assertion issuer, who is presumed to have - been involved without being explicitly named here). - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - - self.authn_context_class_ref = authn_context_class_ref - self.authn_context_decl_ref = authn_context_decl_ref - self.authn_context_decl = authn_context_decl - self.authenticating_authority = authenticating_authority or [] - -def authn_context_from_string(xml_string): - """ Create AuthnContext instance from an XML string """ - return saml2.create_class_from_xml_string(AuthnContext, xml_string) - - -# --------------------------------------------------------------------------- -# AuthnStatement -# --------------------------------------------------------------------------- - -class AuthnStatement(Statement): - """The saml:AuthnStatement element""" - - c_tag = 'AuthnStatement' - c_namespace = NAMESPACE - c_children = Statement.c_children.copy() - c_attributes = Statement.c_attributes.copy() - c_attributes['AuthnInstant'] = 'authn_instant' - c_attributes['SessionIndex'] = 'session_index' - c_attributes['SessionNotOnOrAfter'] = 'session_not_on_or_after' - c_children['{%s}SubjectLocality' % NAMESPACE] = ( - 'subject_locality', SubjectLocality) - c_children['{%s}AuthnContext' % NAMESPACE] = ( - 'authn_context', AuthnContext) - c_child_order = Statement.c_child_order[:] - c_child_order.extend(['subject_locality', 'authn_context']) - - def __init__(self, authn_instant=None, session_index=None, - session_not_on_or_after=None, subject_locality=None, - authn_context=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AuthnStatement - - :param authn_instant: AuthnInstant attribute; Specifies the time at - which the authentication took place. - :param session_index: SessionIndex attribute; Specifies the index of - a particular session between the principal identified by the - subject and the authenticating authority. - :param session_not_on_or_after: SessionNotOnOrAfter attribute; - Specifies a time instant at which the session between the - principal identified by the subject and the SAML authority - issuing this statement MUST be considered ended. - :param subject_locality: SubjectLocality element; Specifies the DNS - domain name and IP address for the system from which the - assertion subject was apparently authenticated. - :param authn_context: AuthnContext element; The context used by the - authenticating authority up to and including the authentication - event that yielded this statement. - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - Statement.__init__(self, text, extension_elements, - extension_attributes ) - - self.authn_instant = authn_instant - self.session_index = session_index - self.session_not_on_or_after = session_not_on_or_after - self.subject_locality = subject_locality - self.authn_context = authn_context - -def authn_statement_from_string(xml_string): - """ Create AuthnStatement instance from an XML string """ - return saml2.create_class_from_xml_string(AuthnStatement, xml_string) - -# --------------------------------------------------------------------------- -# AttributeValue -# --------------------------------------------------------------------------- +def action_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ActionType, xml_string) +# -------------------- AttributeValue -------------------- XSD = "xs:" NS_SOAP_ENC = "http://schemas.xmlsoap.org/soap/encoding/" @@ -880,61 +508,53 @@ def _verify_value_type(typ, val): if typ == XSD + "base64Binary": import base64 return base64.decodestring(val) - + +TYPE_EXTENSION = '{%s}type' % XSI_NAMESPACE + class AttributeValue(SamlBase): - """The saml:AttributeValue element supplies the value of a specified SAML - attribute.""" + """The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element """ c_tag = 'AttributeValue' c_namespace = NAMESPACE + c_value_type = 'anyType' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes[XSI_TYPE] = 'type' + c_child_order = SamlBase.c_child_order[:] - def __init__(self, type=None, text=None, extension_elements=None, - extension_attributes=None): - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.type = type + def set_type(self, typ): + self.extension_attributes[TYPE_EXTENSION] = typ - def harvest_element_tree(self, tree): - typ = tree.attrib.get(XSI_TYPE) - if (typ): - self.text = _decode_attribute_value(typ, tree.text) - else: - self.text = tree.text - - def set_text(self, val, base64encode=False): + def get_type(self): try: - typ = getattr(self, "type") - except: - typ = None - - #print "AV.set_text('%s', %s) [%s]" % (val,base64encode,typ) - + return self.extension_attributes[TYPE_EXTENSION] + except KeyError: + return "" + + def set_text(self, val, base64encode=False): + typ = self.get_type() if base64encode: import base64 val = base64.encodestring(val) - if not typ: - setattr(self, "type", "xs:base64Binary") + self.set_type("xs:base64Binary") else: if isinstance(val, basestring): if not typ: - setattr(self, "type", "xs:string") + self.set_type("xs:string") elif isinstance(val, bool): if val: val = "true" else: val = "false" if not typ: - setattr(self, "type", "xs:boolean") + self.set_type("xs:boolean") elif isinstance(val, int): val = str(val) if not typ: - setattr(self, "type", "xs:integer") + self.set_type("xs:integer") elif isinstance(val, float): val = str(val) if not typ: - setattr(self, "type", "xs:float") + self.set_type("xs:float") elif val == None: val = "" else: @@ -952,433 +572,862 @@ class AttributeValue(SamlBase): if tree.text: #print "set_text:", tree.text self.set_text(tree.text) - _x = _verify_value_type(getattr(self,"type"), getattr(self,"text")) + try: + typ = self.extension_attributes[TYPE_EXTENSION] + _x = _verify_value_type(typ, getattr(self,"text")) + except KeyError: + pass #print _x - + def attribute_value_from_string(xml_string): - """ Create AttributeValue instance from an XML string """ return saml2.create_class_from_xml_string(AttributeValue, xml_string) - -# --------------------------------------------------------------------------- -# EncryptedAttribute -# --------------------------------------------------------------------------- - -class EncryptedAttribute(SamlBase): - """The saml:EncryptedAttribute element represents a SAML attribute in - encrypted fashion, as defined by the XML Encryption Syntax and Processing - specification.""" +class EncryptedAttribute(EncryptedElementType): + """The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element """ c_tag = 'EncryptedAttribute' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() + c_children = EncryptedElementType.c_children.copy() + c_attributes = EncryptedElementType.c_attributes.copy() + c_child_order = EncryptedElementType.c_child_order[:] def encrypted_attribute_from_string(xml_string): - """ Create EncryptedAttribute instance from an XML string """ return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) -# --------------------------------------------------------------------------- -# Attribute -# --------------------------------------------------------------------------- +class BaseID(BaseIDAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element """ -class Attribute(SamlBase): - """The saml:Attribute element""" + c_tag = 'BaseID' + c_namespace = NAMESPACE + c_children = BaseIDAbstractType.c_children.copy() + c_attributes = BaseIDAbstractType.c_attributes.copy() + c_child_order = BaseIDAbstractType.c_child_order[:] - c_tag = 'Attribute' +def base_id_from_string(xml_string): + return saml2.create_class_from_xml_string(BaseID, xml_string) + +class NameID(NameIDType): + """The urn:oasis:names:tc:SAML:2.0:assertion:NameID element """ + + c_tag = 'NameID' + c_namespace = NAMESPACE + c_children = NameIDType.c_children.copy() + c_attributes = NameIDType.c_attributes.copy() + c_child_order = NameIDType.c_child_order[:] + +def name_id_from_string(xml_string): + return saml2.create_class_from_xml_string(NameID, xml_string) + +class SubjectConfirmationData(SubjectConfirmationDataType): + """The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element """ + + c_tag = 'SubjectConfirmationData' + c_namespace = NAMESPACE + c_children = SubjectConfirmationDataType.c_children.copy() + c_attributes = SubjectConfirmationDataType.c_attributes.copy() + c_child_order = SubjectConfirmationDataType.c_child_order[:] + +def subject_confirmation_data_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) + +class Condition(ConditionAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Condition element """ + + c_tag = 'Condition' + c_namespace = NAMESPACE + c_children = ConditionAbstractType.c_children.copy() + c_attributes = ConditionAbstractType.c_attributes.copy() + c_child_order = ConditionAbstractType.c_child_order[:] + +def condition_from_string(xml_string): + return saml2.create_class_from_xml_string(Condition, xml_string) + +class AudienceRestrictionType(ConditionAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element """ + + c_tag = 'AudienceRestrictionType' + c_namespace = NAMESPACE + c_children = ConditionAbstractType.c_children.copy() + c_attributes = ConditionAbstractType.c_attributes.copy() + c_child_order = ConditionAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) + c_child_order.extend(['audience']) + + def __init__(self, + audience=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + ConditionAbstractType.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.audience=audience or [] + +def audience_restriction_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AudienceRestrictionType, xml_string) + +class OneTimeUse(OneTimeUseType): + """The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element """ + + c_tag = 'OneTimeUse' + c_namespace = NAMESPACE + c_children = OneTimeUseType.c_children.copy() + c_attributes = OneTimeUseType.c_attributes.copy() + c_child_order = OneTimeUseType.c_child_order[:] + +def one_time_use_from_string(xml_string): + return saml2.create_class_from_xml_string(OneTimeUse, xml_string) + +class ProxyRestriction(ProxyRestrictionType): + """The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element """ + + c_tag = 'ProxyRestriction' + c_namespace = NAMESPACE + c_children = ProxyRestrictionType.c_children.copy() + c_attributes = ProxyRestrictionType.c_attributes.copy() + c_child_order = ProxyRestrictionType.c_child_order[:] + +def proxy_restriction_from_string(xml_string): + return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) + +class Statement(StatementAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Statement element """ + + c_tag = 'Statement' + c_namespace = NAMESPACE + c_children = StatementAbstractType.c_children.copy() + c_attributes = StatementAbstractType.c_attributes.copy() + c_child_order = StatementAbstractType.c_child_order[:] + +def statement_from_string(xml_string): + return saml2.create_class_from_xml_string(Statement, xml_string) + +class SubjectLocality(SubjectLocalityType): + """The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element """ + + c_tag = 'SubjectLocality' + c_namespace = NAMESPACE + c_children = SubjectLocalityType.c_children.copy() + c_attributes = SubjectLocalityType.c_attributes.copy() + c_child_order = SubjectLocalityType.c_child_order[:] + +def subject_locality_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectLocality, xml_string) + +class AuthnContextType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element """ + + c_tag = 'AuthnContextType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['Name'] = 'name' - c_attributes['NameFormat'] = 'name_format' - c_attributes['FriendlyName'] = 'friendly_name' - c_children['{%s}AttributeValue' % NAMESPACE] = ('attribute_value', - [AttributeValue]) - - def __init__(self, name=None, name_format=None, friendly_name=None, - attribute_value=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for Attribute + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ('authn_context_class_ref', AuthnContextClassRef) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = ('authn_context_decl', AuthnContextDecl) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ('authn_context_decl_ref', AuthnContextDeclRef) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = ('authenticating_authority', [AuthenticatingAuthority]) + c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority']) - :param name: The name of the attribute. - :param name_format: NameFormat attribute, A URI reference representing - the classification of the attribute name for purposes of - interpreting the name. - :param friendly_name: FriendlyName attribute; A string that provides a - more human-readable form of the attribute's name, which may be - useful in cases in which the actual Name is complex or opaque, - such as an OID or a UUID. - :param attribute_value: AttributeValue elements, Contains a value of - the attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ + def __init__(self, + authn_context_class_ref=None, + authn_context_decl=None, + authn_context_decl_ref=None, + authenticating_authority=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.authn_context_class_ref=authn_context_class_ref + self.authn_context_decl=authn_context_decl + self.authn_context_decl_ref=authn_context_decl_ref + self.authenticating_authority=authenticating_authority or [] - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.name = name - self.name_format = name_format - self.friendly_name = friendly_name - self.attribute_value = attribute_value or [] +def authn_context_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnContextType, xml_string) -def attribute_from_string(xml_string): - """ Create Attribute instance from an XML string """ - return saml2.create_class_from_xml_string(Attribute, xml_string) - -# --------------------------------------------------------------------------- -# AttributeStatement -# --------------------------------------------------------------------------- - -class AttributeStatement(Statement): - """The saml:AttributeStatement element describes a statement by the SAML - authority asserting that the assertion subject is associated with the - specified attributes.""" - - c_tag = 'AttributeStatement' - c_namespace = NAMESPACE - c_children = Statement.c_children.copy() - c_attributes = Statement.c_attributes.copy() - c_children['{%s}Attribute' % NAMESPACE] = ('attribute', [Attribute]) - c_children['{%s}EncryptedAttribute' % NAMESPACE] = ( - 'encrypted_attribute', [EncryptedAttribute]) - c_child_order = Statement.c_child_order[:] - c_child_order.extend(['attribute', 'encrypted_attribute']) - - def __init__(self, attribute=None, encrypted_attribute=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AttributeStatement - - :param attribute: Attribute elements - :param encrypted_attribute: EncryptedAttribute elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - Statement.__init__(self, text, extension_elements, - extension_attributes) - self.attribute = attribute or [] - self.encrypted_attribute = encrypted_attribute or [] - -def attribute_statement_from_string(xml_string): - """ Create AttributeStatement instance from an XML string """ - return saml2.create_class_from_xml_string(AttributeStatement, xml_string) - -# --------------------------------------------------------------------------- -# Action -# --------------------------------------------------------------------------- - -class Action(SamlBase): - """The saml:Action element specifies an action on the specified resource - for which permission is sought.""" +class Action(ActionType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Action element """ c_tag = 'Action' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['Namespace'] = 'namespace' - - def __init__(self, namespace=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for Action - - :param namespace: Namespace attribute; A URI reference representing the - namespace in which the name of the specified action is to be - interpreted. - :param text: The text data in this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.namespace = namespace + c_children = ActionType.c_children.copy() + c_attributes = ActionType.c_attributes.copy() + c_child_order = ActionType.c_child_order[:] def action_from_string(xml_string): - """ Create Action instance from an XML string """ return saml2.create_class_from_xml_string(Action, xml_string) -# --------------------------------------------------------------------------- -# Evidence -# --------------------------------------------------------------------------- +class AttributeType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element """ -class Evidence(SamlBase): - """The saml:Evidence element contains one or more assertions or - assertion references that the SAML authority relied on in issuing - the authorization decision.""" - - c_tag = 'Evidence' + c_tag = 'AttributeType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_children['{%s}AssertionIDRef' % NAMESPACE] = ('assertion_id_ref', - [AssertionIDRef]) - c_children['{%s}AssertionURIRef' % NAMESPACE] = ('assertion_uri_ref', - [AssertionURIRef]) - # Can't do this here since Assertion isn't defined - #c_children['{%s}Assertion' % NAMESPACE] = ('assertion', [Assertion]) - c_children['{%s}EncryptedAssertion' % NAMESPACE] = ( - 'encrypted_assertion', [EncryptedAssertion]) - c_child_order = ['assertion_id_ref', 'assertion_uri_ref', 'assertion', - 'encrypted_assertion'] - - def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, - assertion=None, encrypted_assertion=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for Evidence + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = ('attribute_value', [AttributeValue]) + c_attributes['Name'] = ('name', 'string', True) + c_attributes['NameFormat'] = ('name_format', 'anyURI', False) + c_attributes['FriendlyName'] = ('friendly_name', 'string', False) + c_child_order.extend(['attribute_value']) - :param assertion_id_ref: AssertionIDRef elements - :param assertion_uri_ref: AssertionURIRef elements - :param assertion: Assertion elements - :param encrypted_assertion: EncryptedAssertion elements - :param text: The text data in this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ + def __init__(self, + attribute_value=None, + name=None, + name_format=None, + friendly_name=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.attribute_value=attribute_value or [] + self.name=name + self.name_format=name_format + self.friendly_name=friendly_name - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.assertion_id_ref = assertion_id_ref or [] - self.assertion_uri_ref = assertion_uri_ref or [] - self.assertion = assertion or [] - self.encrypted_assertion = encrypted_assertion or [] +def attribute_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeType, xml_string) -def evidence_from_string(xml_string): - """ Create Evidence instance from an XML string """ - return saml2.create_class_from_xml_string(Evidence, xml_string) +class SubjectConfirmationType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element """ + c_tag = 'SubjectConfirmationType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ('encrypted_id', EncryptedID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = ('subject_confirmation_data', SubjectConfirmationData) + c_attributes['Method'] = ('method', 'anyURI', True) + c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation_data']) -# --------------------------------------------------------------------------- -# AuthzDecisionStatement -# --------------------------------------------------------------------------- + def __init__(self, + base_id=None, + name_id=None, + encrypted_id=None, + subject_confirmation_data=None, + method=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.base_id=base_id + self.name_id=name_id + self.encrypted_id=encrypted_id + self.subject_confirmation_data=subject_confirmation_data + self.method=method -class AuthzDecisionStatement(Statement): - """The saml:AuthzDecisionStatement element describes a statement by the - SAML authority asserting that a request for access by the assertion subject - to the specified resource has resulted in the specified authorization - decision on the basis of some optionally specified evidence.""" +def subject_confirmation_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectConfirmationType, xml_string) + +class AudienceRestriction(AudienceRestrictionType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element """ + + c_tag = 'AudienceRestriction' + c_namespace = NAMESPACE + c_children = AudienceRestrictionType.c_children.copy() + c_attributes = AudienceRestrictionType.c_attributes.copy() + c_child_order = AudienceRestrictionType.c_child_order[:] + +def audience_restriction_from_string(xml_string): + return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) + +class AuthnContext(AuthnContextType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element """ + + c_tag = 'AuthnContext' + c_namespace = NAMESPACE + c_children = AuthnContextType.c_children.copy() + c_attributes = AuthnContextType.c_attributes.copy() + c_child_order = AuthnContextType.c_child_order[:] + +def authn_context_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnContext, xml_string) + +class Attribute(AttributeType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element """ + + c_tag = 'Attribute' + c_namespace = NAMESPACE + c_children = AttributeType.c_children.copy() + c_attributes = AttributeType.c_attributes.copy() + c_child_order = AttributeType.c_child_order[:] + +def attribute_from_string(xml_string): + return saml2.create_class_from_xml_string(Attribute, xml_string) + +class SubjectConfirmation(SubjectConfirmationType): + """The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element """ + + c_tag = 'SubjectConfirmation' + c_namespace = NAMESPACE + c_children = SubjectConfirmationType.c_children.copy() + c_attributes = SubjectConfirmationType.c_attributes.copy() + c_child_order = SubjectConfirmationType.c_child_order[:] + +def subject_confirmation_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) + +class ConditionsType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element """ + + c_tag = 'ConditionsType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = ('condition', [Condition]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = ('audience_restriction', [AudienceRestriction]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = ('one_time_use', [OneTimeUse]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = ('proxy_restriction', [ProxyRestriction]) + c_attributes['NotBefore'] = ('not_before', 'dateTime', False) + c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) + c_child_order.extend(['condition', 'audience_restriction', 'one_time_use', 'proxy_restriction']) + + def __init__(self, + condition=None, + audience_restriction=None, + one_time_use=None, + proxy_restriction=None, + not_before=None, + not_on_or_after=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.condition=condition or [] + self.audience_restriction=audience_restriction or [] + self.one_time_use=one_time_use or [] + self.proxy_restriction=proxy_restriction or [] + self.not_before=not_before + self.not_on_or_after=not_on_or_after + +def conditions_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ConditionsType, xml_string) + +class AuthnStatementType(StatementAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element """ + + c_tag = 'AuthnStatementType' + c_namespace = NAMESPACE + c_children = StatementAbstractType.c_children.copy() + c_attributes = StatementAbstractType.c_attributes.copy() + c_child_order = StatementAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = ('subject_locality', SubjectLocality) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = ('authn_context', AuthnContext) + c_attributes['AuthnInstant'] = ('authn_instant', 'dateTime', True) + c_attributes['SessionIndex'] = ('session_index', 'string', False) + c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after', 'dateTime', False) + c_child_order.extend(['subject_locality', 'authn_context']) + + def __init__(self, + subject_locality=None, + authn_context=None, + authn_instant=None, + session_index=None, + session_not_on_or_after=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + StatementAbstractType.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.subject_locality=subject_locality + self.authn_context=authn_context + self.authn_instant=authn_instant + self.session_index=session_index + self.session_not_on_or_after=session_not_on_or_after + +def authn_statement_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnStatementType, xml_string) + +class AttributeStatementType(StatementAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element """ + + c_tag = 'AttributeStatementType' + c_namespace = NAMESPACE + c_children = StatementAbstractType.c_children.copy() + c_attributes = StatementAbstractType.c_attributes.copy() + c_child_order = StatementAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ('attribute', [Attribute]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = ('encrypted_attribute', [EncryptedAttribute]) + c_child_order.extend(['attribute', 'encrypted_attribute']) + + def __init__(self, + attribute=None, + encrypted_attribute=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + StatementAbstractType.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.attribute=attribute or [] + self.encrypted_attribute=encrypted_attribute or [] + +def attribute_statement_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeStatementType, xml_string) + +class SubjectType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element """ + + c_tag = 'SubjectType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ('encrypted_id', EncryptedID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = ('subject_confirmation', [SubjectConfirmation]) + c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation']) + + def __init__(self, + base_id=None, + name_id=None, + encrypted_id=None, + subject_confirmation=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.base_id=base_id + self.name_id=name_id + self.encrypted_id=encrypted_id + self.subject_confirmation=subject_confirmation or [] + +def subject_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectType, xml_string) + +class Conditions(ConditionsType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element """ + + c_tag = 'Conditions' + c_namespace = NAMESPACE + c_children = ConditionsType.c_children.copy() + c_attributes = ConditionsType.c_attributes.copy() + c_child_order = ConditionsType.c_child_order[:] + +def conditions_from_string(xml_string): + return saml2.create_class_from_xml_string(Conditions, xml_string) + +class AuthnStatement(AuthnStatementType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element """ + + c_tag = 'AuthnStatement' + c_namespace = NAMESPACE + c_children = AuthnStatementType.c_children.copy() + c_attributes = AuthnStatementType.c_attributes.copy() + c_child_order = AuthnStatementType.c_child_order[:] + +def authn_statement_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnStatement, xml_string) + +class AttributeStatement(AttributeStatementType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element """ + + c_tag = 'AttributeStatement' + c_namespace = NAMESPACE + c_children = AttributeStatementType.c_children.copy() + c_attributes = AttributeStatementType.c_attributes.copy() + c_child_order = AttributeStatementType.c_child_order[:] + +def attribute_statement_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeStatement, xml_string) + +class Subject(SubjectType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Subject element """ + + c_tag = 'Subject' + c_namespace = NAMESPACE + c_children = SubjectType.c_children.copy() + c_attributes = SubjectType.c_attributes.copy() + c_child_order = SubjectType.c_child_order[:] + +def subject_from_string(xml_string): + return saml2.create_class_from_xml_string(Subject, xml_string) + +#.................. +# ['AssertionType', 'Advice', 'Assertion', 'AuthzDecisionStatementType', 'AuthzDecisionStatement', 'EvidenceType', 'Evidence', 'AdviceType'] +class AuthzDecisionStatementType(StatementAbstractType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element """ + + c_tag = 'AuthzDecisionStatementType' + c_namespace = NAMESPACE + c_children = StatementAbstractType.c_children.copy() + c_attributes = StatementAbstractType.c_attributes.copy() + c_child_order = StatementAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ('action', [Action]) + c_attributes['Resource'] = ('resource', 'anyURI', True) + c_attributes['Decision'] = ('decision', 'DecisionType', True) + c_child_order.extend(['action', 'evidence']) + + def __init__(self, + action=None, + evidence=None, + resource=None, + decision=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + StatementAbstractType.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.action=action or [] + self.evidence=evidence + self.resource=resource + self.decision=decision + +def authz_decision_statement_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthzDecisionStatementType, xml_string) + +class AuthzDecisionStatement(AuthzDecisionStatementType): + """The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element """ c_tag = 'AuthzDecisionStatement' c_namespace = NAMESPACE - c_children = Statement.c_children.copy() - c_attributes = Statement.c_attributes.copy() - - c_attributes['Resource'] = 'resource' - c_attributes['Decision'] = 'decision' - c_children['{%s}Action' % NAMESPACE] = ('action', [Action]) - c_children['{%s}Evidence' % NAMESPACE] = ('evidence', [Evidence]) - c_child_order = Statement.c_child_order[:] - c_child_order.extend(['action', 'evidence']) - - def __init__(self, resource=None, decision=None, action=None, - evidence=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AuthzDecisionStatement - - :param text: str The text data in this element - :param resource: Resource attribute; A URI reference identifying - the resource to which access authorization is sought. - :param decision: Decision attribute; The decision rendered by the - SAML authority with respect to the specified resource. - :param action: Action Elements; The set of actions authorized to - be performed on the specified resource. - :param evidence: Evidence Elements; A set of assertions that the - SAML authority relied on in making the decision. - :param text: The text data in this element - :param extension_elements:A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - Statement.__init__(self, text, extension_elements, - extension_attributes) - self.resource = resource - self.decision = decision - self.action = action or [] - self.evidence = evidence or [] + c_children = AuthzDecisionStatementType.c_children.copy() + c_attributes = AuthzDecisionStatementType.c_attributes.copy() + c_child_order = AuthzDecisionStatementType.c_child_order[:] def authz_decision_statement_from_string(xml_string): - """ Create AuthzDecisionStatement instance from an XML string """ - return saml2.create_class_from_xml_string(AuthzDecisionStatement, - xml_string) + return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) -# --------------------------------------------------------------------------- -# Assertion -# --------------------------------------------------------------------------- +#.................. +# ['AssertionType', 'Advice', 'Assertion', 'EvidenceType', 'AdviceType', 'Evidence'] +class AssertionType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element """ -class Assertion(SamlBase): - """The saml:Assertion element""" - c_tag = 'Assertion' + c_tag = 'AssertionType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['Version'] = 'version' - c_attributes['ID'] = 'id' - c_attributes['IssueInstant'] = 'issue_instant' - c_children['{%s}Issuer' % NAMESPACE] = ('issuer', Issuer) - c_children['{%s}Signature' % ds.NAMESPACE] = ('signature', ds.Signature) - c_children['{%s}Subject' % NAMESPACE] = ('subject', Subject) - c_children['{%s}Conditions' % NAMESPACE] = ('conditions', Conditions) - #c_children['{%s}Advice' % NAMESPACE] = ('advice', Advice) - c_children['{%s}Statement' % NAMESPACE] = ('statement', [Statement]) - c_children['{%s}AuthnStatement' % NAMESPACE] = ( - 'authn_statement', [AuthnStatement]) - c_children['{%s}AuthzDecisionStatement' % NAMESPACE] = ( - 'authz_decision_statement', [AuthzDecisionStatement]) - c_children['{%s}AttributeStatement' % NAMESPACE] = ( - 'attribute_statement', [AttributeStatement]) - c_child_order = ['issuer', 'signature', 'subject', 'conditions', 'advice', - 'statement', 'authn_statement', 'authz_decision_statement', - 'attribute_statement'] + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', Issuer) + c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', Subject) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ('conditions', Conditions) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = ('statement', [Statement]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = ('authn_statement', [AuthnStatement]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = ('authz_decision_statement', [AuthzDecisionStatement]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = ('attribute_statement', [AttributeStatement]) + c_attributes['Version'] = ('version', 'string', True) + c_attributes['ID'] = ('id', 'ID', True) + c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True) + c_child_order.extend(['issuer', 'signature', 'subject', 'conditions', 'advice', 'statement', 'authn_statement', 'authz_decision_statement', 'attribute_statement']) - def __init__(self, version=None, id=None, issue_instant=None, - issuer=None, signature=None, subject=None, conditions=None, - advice=None, statement=None, authn_statement=None, - authz_decision_statement=None, attribute_statement=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for Assertion + def __init__(self, + issuer=None, + signature=None, + subject=None, + conditions=None, + advice=None, + statement=None, + authn_statement=None, + authz_decision_statement=None, + attribute_statement=None, + version=None, + id=None, + issue_instant=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.issuer=issuer + self.signature=signature + self.subject=subject + self.conditions=conditions + self.advice=advice + self.statement=statement or [] + self.authn_statement=authn_statement or [] + self.authz_decision_statement=authz_decision_statement or [] + self.attribute_statement=attribute_statement or [] + self.version=version + self.id=id + self.issue_instant=issue_instant - :param version: Version attribute; The version of this assertion. - The identifier for the version of SAML defined in this - specification is "2.0". - :param id: ID attribute, The identifier for this assertion. - :param issue_instant: IssueInstant attribute; The time instant of - issue in UTC. - :param issuer: Issuer element; The SAML authority that is making - the claim(s) in the assertion. - :param signature: ds:Signature element; An XML Signature that - protects the integrity of and authenticates the issuer of - the assertion - :param subject: Subject element; The subject of the statement(s) - in the assertion. - :param conditions: Conditions element; Conditions that MUST be - evaluated when assessing the validity of and/or when using - the assertion. - :param advice: Advice element; Additional information related - to the assertion that assists processing in certain - situations but which MAY be ignored by applications that do not - understand the advice or do not wish to make use of it. - :param statement: Statement elements; A statement of a type - defined in an extension schema. An xsi:type attribute MUST - be used to indicate the actual statement type. - :param authn_statement: AuthnStatement elements; An authentication - statement. - :param authz_decision_statement: AuthzDecisionStatement elements; - An authorization decision statement - :param attribute_statement: AttributeStatement elements: - An attribute statement. - :param text: The text data in this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +def assertion_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AssertionType, xml_string) - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.version = version - self.id = id - self.issue_instant = issue_instant - self.issuer = issuer - self.signature = signature - self.subject = subject - self.conditions = conditions - self.advice = advice - self.statement = statement or [] - self.authn_statement = authn_statement or [] - self.authz_decision_statement = authz_decision_statement or [] - self.attribute_statement = attribute_statement or [] +class Assertion(AssertionType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element """ + + c_tag = 'Assertion' + c_namespace = NAMESPACE + c_children = AssertionType.c_children.copy() + c_attributes = AssertionType.c_attributes.copy() + c_child_order = AssertionType.c_child_order[:] def assertion_from_string(xml_string): - """ Create Assertion instance from an XML string """ return saml2.create_class_from_xml_string(Assertion, xml_string) -Evidence.c_children['{%s}Assertion' % NAMESPACE] = ( - 'assertion', [Assertion]) +class AdviceType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element """ -# --------------------------------------------------------------------------- -# Advice -# --------------------------------------------------------------------------- + c_tag = 'AdviceType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ('assertion_id_ref', [AssertionIDRef]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ('assertion_uri_ref', [AssertionURIRef]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ('assertion', [Assertion]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ('encrypted_assertion', [EncryptedAssertion]) + c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) -class Advice(SamlBase): - """The saml:Advice element contains any additional information that the - SAML authority wishes to provide.""" + def __init__(self, + assertion_id_ref=None, + assertion_uri_ref=None, + assertion=None, + encrypted_assertion=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.assertion_id_ref=assertion_id_ref or [] + self.assertion_uri_ref=assertion_uri_ref or [] + self.assertion=assertion or [] + self.encrypted_assertion=encrypted_assertion or [] + +def advice_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AdviceType, xml_string) + +class EvidenceType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element """ + + c_tag = 'EvidenceType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ('assertion_id_ref', [AssertionIDRef]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ('assertion_uri_ref', [AssertionURIRef]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ('assertion', [Assertion]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ('encrypted_assertion', [EncryptedAssertion]) + c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) + + def __init__(self, + assertion_id_ref=None, + assertion_uri_ref=None, + assertion=None, + encrypted_assertion=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.assertion_id_ref=assertion_id_ref or [] + self.assertion_uri_ref=assertion_uri_ref or [] + self.assertion=assertion or [] + self.encrypted_assertion=encrypted_assertion or [] + +def evidence_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EvidenceType, xml_string) + +class Advice(AdviceType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Advice element """ c_tag = 'Advice' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_children['{%s}AssertionIDRef' % NAMESPACE] = ('assertion_id_ref', - [AssertionIDRef]) - c_children['{%s}AssertionURIRef' % NAMESPACE] = ('assertion_uri_ref', - [AssertionURIRef]) - c_children['{%s}Assertion' % NAMESPACE] = ('assertion', [Assertion]) - c_children['{%s}EncryptedAssertion' % NAMESPACE] = ( - 'encrypted_assertion', [EncryptedAssertion]) - c_child_order = ['assertion_id_ref', 'assertion_uri_ref', - 'assertion', 'encrypted_assertion'] - - def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, - assertion=None, encrypted_assertion=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for Advice - - :param assertion_id_ref: AssertionIDRef elements - :param assertion_uri_ref: AssertionURIRef elements - :param assertion: Assertion elements - :param encrypted_assertion: EncryptedAssertion elements - :param text: The text data in this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.assertion_id_ref = assertion_id_ref or [] - self.assertion_uri_ref = assertion_uri_ref or [] - self.assertion = assertion or [] - self.encrypted_assertion = encrypted_assertion or [] + c_children = AdviceType.c_children.copy() + c_attributes = AdviceType.c_attributes.copy() + c_child_order = AdviceType.c_child_order[:] def advice_from_string(xml_string): - """ Create Advice instance from an XML string """ return saml2.create_class_from_xml_string(Advice, xml_string) -Assertion.c_children['{%s}Advice' % NAMESPACE] = ('advice', Advice) -Evidence.c_children['{%s}Assertion' % NAMESPACE] = ('assertion', [Assertion]) +class Evidence(EvidenceType): + """The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element """ + + c_tag = 'Evidence' + c_namespace = NAMESPACE + c_children = EvidenceType.c_children.copy() + c_attributes = EvidenceType.c_attributes.copy() + c_child_order = EvidenceType.c_child_order[:] + +def evidence_from_string(xml_string): + return saml2.create_class_from_xml_string(Evidence, xml_string) + +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +AuthzDecisionStatementType.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ('evidence', Evidence) +AuthzDecisionStatement.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ('evidence', Evidence) +AssertionType.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ('advice', Advice) +Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ('advice', Advice) +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ELEMENT_FROM_STRING = { BaseID.c_tag: base_id_from_string, + BaseIDAbstractType.c_tag: base_id_abstract_type_from_string, NameID.c_tag: name_id_from_string, + NameIDType.c_tag: name_id_type_from_string, + EncryptedElementType.c_tag: encrypted_element_type_from_string, EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string, - EncryptedAssertion.c_tag: encrypted_assertion_from_string, - SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, - SubjectConfirmation.c_tag: subject_confirmation_from_string, + Assertion.c_tag: assertion_from_string, + AssertionType.c_tag: assertion_type_from_string, Subject.c_tag: subject_from_string, - Condition.c_tag: condition_from_string, - Audience.c_tag: audience_from_string, - AudienceRestriction.c_tag: audience_restriction_from_string, - OneTimeUse.c_tag: one_time_use_from_string, - ProxyRestriction.c_tag: proxy_restriction_from_string, + SubjectType.c_tag: subject_type_from_string, + SubjectConfirmation.c_tag: subject_confirmation_from_string, + SubjectConfirmationType.c_tag: subject_confirmation_type_from_string, + SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, + SubjectConfirmationDataType.c_tag: subject_confirmation_data_type_from_string, + KeyInfoConfirmationDataType.c_tag: key_info_confirmation_data_type_from_string, Conditions.c_tag: conditions_from_string, + ConditionsType.c_tag: conditions_type_from_string, + Condition.c_tag: condition_from_string, + ConditionAbstractType.c_tag: condition_abstract_type_from_string, + AudienceRestriction.c_tag: audience_restriction_from_string, + AudienceRestrictionType.c_tag: audience_restriction_type_from_string, + Audience.c_tag: audience_from_string, + OneTimeUse.c_tag: one_time_use_from_string, + OneTimeUseType.c_tag: one_time_use_type_from_string, + ProxyRestriction.c_tag: proxy_restriction_from_string, + ProxyRestrictionType.c_tag: proxy_restriction_type_from_string, + Advice.c_tag: advice_from_string, + AdviceType.c_tag: advice_type_from_string, + EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag: statement_from_string, + StatementAbstractType.c_tag: statement_abstract_type_from_string, + AuthnStatement.c_tag: authn_statement_from_string, + AuthnStatementType.c_tag: authn_statement_type_from_string, SubjectLocality.c_tag: subject_locality_from_string, + SubjectLocalityType.c_tag: subject_locality_type_from_string, + AuthnContext.c_tag: authn_context_from_string, + AuthnContextType.c_tag: authn_context_type_from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string, - AuthnContext.c_tag: authn_context_from_string, - AuthnStatement(Statement): authn_statement_from_string, + AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, + AuthzDecisionStatementType.c_tag: authz_decision_statement_type_from_string, + DecisionType.c_tag: decision_type_from_string, + Action.c_tag: action_from_string, + ActionType.c_tag: action_type_from_string, + Evidence.c_tag: evidence_from_string, + EvidenceType.c_tag: evidence_type_from_string, + AttributeStatement.c_tag: attribute_statement_from_string, + AttributeStatementType.c_tag: attribute_statement_type_from_string, + Attribute.c_tag: attribute_from_string, + AttributeType.c_tag: attribute_type_from_string, AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string, - Attribute.c_tag: attribute_from_string, - AttributeStatement(Statement): attribute_statement_from_string, - Action.c_tag: action_from_string, - Evidence.c_tag: evidence_from_string, - AuthzDecisionStatement(Statement): authz_decision_statement_from_string, - Assertion.c_tag: assertion_from_string, - Advice.c_tag: advice_from_string, -} \ No newline at end of file +} + +ELEMENT_BY_TAG = { + 'BaseID': BaseID, + 'BaseIDAbstractType': BaseIDAbstractType, + 'NameID': NameID, + 'NameIDType': NameIDType, + 'EncryptedElementType': EncryptedElementType, + 'EncryptedID': EncryptedID, + 'Issuer': Issuer, + 'AssertionIDRef': AssertionIDRef, + 'AssertionURIRef': AssertionURIRef, + 'Assertion': Assertion, + 'AssertionType': AssertionType, + 'Subject': Subject, + 'SubjectType': SubjectType, + 'SubjectConfirmation': SubjectConfirmation, + 'SubjectConfirmationType': SubjectConfirmationType, + 'SubjectConfirmationData': SubjectConfirmationData, + 'SubjectConfirmationDataType': SubjectConfirmationDataType, + 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType, + 'Conditions': Conditions, + 'ConditionsType': ConditionsType, + 'Condition': Condition, + 'ConditionAbstractType': ConditionAbstractType, + 'AudienceRestriction': AudienceRestriction, + 'AudienceRestrictionType': AudienceRestrictionType, + 'Audience': Audience, + 'OneTimeUse': OneTimeUse, + 'OneTimeUseType': OneTimeUseType, + 'ProxyRestriction': ProxyRestriction, + 'ProxyRestrictionType': ProxyRestrictionType, + 'Advice': Advice, + 'AdviceType': AdviceType, + 'EncryptedAssertion': EncryptedAssertion, + 'Statement': Statement, + 'StatementAbstractType': StatementAbstractType, + 'AuthnStatement': AuthnStatement, + 'AuthnStatementType': AuthnStatementType, + 'SubjectLocality': SubjectLocality, + 'SubjectLocalityType': SubjectLocalityType, + 'AuthnContext': AuthnContext, + 'AuthnContextType': AuthnContextType, + 'AuthnContextClassRef': AuthnContextClassRef, + 'AuthnContextDeclRef': AuthnContextDeclRef, + 'AuthnContextDecl': AuthnContextDecl, + 'AuthenticatingAuthority': AuthenticatingAuthority, + 'AuthzDecisionStatement': AuthzDecisionStatement, + 'AuthzDecisionStatementType': AuthzDecisionStatementType, + 'DecisionType': DecisionType, + 'Action': Action, + 'ActionType': ActionType, + 'Evidence': Evidence, + 'EvidenceType': EvidenceType, + 'AttributeStatement': AttributeStatement, + 'AttributeStatementType': AttributeStatementType, + 'Attribute': Attribute, + 'AttributeType': AttributeType, + 'AttributeValue': AttributeValue, + 'EncryptedAttribute': EncryptedAttribute, +} + +def factory(tag, **kwargs): + return ELEMENT_BY_TAG[tag](**kwargs) + diff --git a/src/saml2/samlp.py b/src/saml2/samlp.py index 83407ce..b4744be 100644 --- a/src/saml2/samlp.py +++ b/src/saml2/samlp.py @@ -1,34 +1,16 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright (C) 2007 SIOS Technology, Inc. -# 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. +#!/usr/bin/env python -"""Contains classes representing Samlp elements. +# +# Generated Thu Jul 15 21:40:22 2010 by parse_xsd.py version 0.3. +# - Module objective: provide data classes for Samlp constructs. These - classes hide the XML-ness of Saml and provide a set of native Python - classes to interact with. - -""" - -from saml2 import saml, SamlBase, create_class_from_xml_string +import saml2 import xmldsig as ds +from saml2 import SamlBase +from saml2 import saml + NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:protocol' -TEMPLATE = '{urn:oasis:names:tc:SAML:2.0:protocol}%s' STATUS_SUCCESS = 'urn:oasis:names:tc:SAML:2.0:status:Success' STATUS_REQUESTER = 'urn:oasis:names:tc:SAML:2.0:status:Requester' @@ -67,1212 +49,1528 @@ STATUS_UNKNOWN_PRINCIPAL = ( STATUS_UNSUPPORTED_BINDING = ( 'urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding') -class Extensions(SamlBase): - """The samlp:Extensions element""" - c_tag = 'Extensions' +class ExtensionsType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:ExtensionsType element """ + + c_tag = 'ExtensionsType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def extensions_from_string(xml_string): - """ Create Extensions instance from an XML string """ - return create_class_from_xml_string(Extensions, xml_string) - -# -------------------------------------------------------------------------- -# 3.2.1 -# -------------------------------------------------------------------------- - -class AbstractRequest(SamlBase): - """The samlp:RequestAbstractType element""" - - c_tag = 'AbstractRequest' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['ID'] = 'id' - c_attributes['Version'] = 'version' - c_attributes['IssueInstant'] = 'issue_instant' - c_attributes['Destination'] = 'destination' - c_attributes['Consent'] = 'consent' - c_children['{%s}Issuer' % saml.NAMESPACE] = ('issuer', saml.Issuer) - c_children['{%s}Signature' % ds.NAMESPACE] = ('signature', ds.Signature) - c_children['{%s}Extensions' % NAMESPACE] = ('extensions', Extensions) - c_child_order = ['issuer', 'signature', 'extensions'] - - def __init__(self, id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, - signature=None, extensions=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for AbstractRequest - - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SamlBase.__init__(self, - text, extension_elements, extension_attributes) - self.id = id - self.version = version - self.issue_instant = issue_instant - self.destination = destination - self.consent = consent - self.issuer = issuer - self.signature = signature - self.extensions = extensions - -def abstract_request_from_string(xml_string): - """ Create AbstractRequest instance from an XML string """ - return create_class_from_xml_string(AbstractRequest, xml_string) - -# -------------------------------------------------------------------------- -# 3.2.2.2 StatusCode -# -------------------------------------------------------------------------- - -class StatusCode(SamlBase): - """The samlp:StatusCode element""" - c_tag = 'StatusCode' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['Value'] = 'value' - # should be here but will be found further down - #c_children['{%s}StatusCode' % NAMESPACE] = ('status_code', StatusCode) - - def __init__(self, value=None, status_code=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for Status - - :param value: Value attribute - :param status_code: StatusCode element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.value = value - self.status_code = status_code - -def status_code_from_string(xml_string): - """ Create StatusCode instance from an XML string """ - return create_class_from_xml_string(StatusCode, xml_string) - -StatusCode.c_children['{%s}StatusCode' % NAMESPACE] = ( - 'status_code', StatusCode) - -# -------------------------------------------------------------------------- -# 3.2.2.3 StatusMessage -# -------------------------------------------------------------------------- +def extensions_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ExtensionsType, xml_string) class StatusMessage(SamlBase): - """The samlp:StatusMessage element""" + """The urn:oasis:names:tc:SAML:2.0:protocol:StatusMessage element """ + c_tag = 'StatusMessage' c_namespace = NAMESPACE + c_value_type = 'string' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def status_message_from_string(xml_string): - """ Create StatusMessage instance from an XML string """ - return create_class_from_xml_string(StatusMessage, xml_string) + return saml2.create_class_from_xml_string(StatusMessage, xml_string) -# -------------------------------------------------------------------------- -# 3.2.2.4 StatusDetail -# -------------------------------------------------------------------------- +class StatusDetailType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:StatusDetailType element """ -class StatusDetail(SamlBase): - """The samlp:StatusDetail element""" - c_tag = 'StatusDetail' + c_tag = 'StatusDetailType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def status_detail_from_string(xml_string): - """ Create StatusDetail instance from an XML string """ - return create_class_from_xml_string(StatusDetail, xml_string) +def status_detail_type_from_string(xml_string): + return saml2.create_class_from_xml_string(StatusDetailType, xml_string) -# -------------------------------------------------------------------------- -# 3.2.2.1 Status -# -------------------------------------------------------------------------- +class RequestedAuthnContextType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:RequestedAuthnContextType element """ -class Status(SamlBase): - """The samlp:Status element""" - - c_tag = 'Status' + c_tag = 'RequestedAuthnContextType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_children['{%s}StatusCode' % NAMESPACE] = ('status_code', StatusCode) - c_children['{%s}StatusMessage' % NAMESPACE] = ( - 'status_message', StatusMessage) - c_children['{%s}StatusDetail' % NAMESPACE] = ( - 'status_detail', StatusDetail) - c_child_order = ['status_code', 'status_message', 'status_detail'] - - def __init__(self, status_code=None, status_message=None, - status_detail=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for Status - - :param status_code: StatusCode element - :param status_message: StatusMessage element - :param status_detail: StatusDetail element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.status_code = status_code - self.status_message = status_message - self.status_detail = status_detail - -def status_from_string(xml_string): - """ Create Status instance from an XML string """ - return create_class_from_xml_string(Status, xml_string) - -# -------------------------------------------------------------------------- -# 3.2.2 -# -------------------------------------------------------------------------- - -class StatusResponse(SamlBase): - """The samlp:StatusResponse element""" - - c_tag = 'StatusResponse' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['ID'] = 'id' - c_attributes['InResponseTo'] = 'in_response_to' - c_attributes['Version'] = 'version' - c_attributes['IssueInstant'] = 'issue_instant' - c_attributes['Destination'] = 'destination' - c_attributes['Consent'] = 'consent' - c_children['{%s}Issuer' % saml.NAMESPACE] = ( - 'issuer', saml.Issuer) - c_children['{%s}Signature' % ds.NAMESPACE] = ( - 'signature', ds.Signature) - c_children['{%s}Extensions' % NAMESPACE] = ( - 'extensions', Extensions) - c_children['{%s}Status' % NAMESPACE] = ('status', Status) - c_child_order = ['issuer', 'signature', 'extensions', 'status'] - - def __init__(self, id=None, in_response_to=None, version=None, - issue_instant=None, destination=None, consent=None, - issuer=None, signature=None, extensions=None, status=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for StatusResponse - - :param id: ID attribute - :param in_respones_to: InResponseTo attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param status: Status element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value - string pairs - """ - - SamlBase.__init__(self, text, extension_elements, - extension_attributes) - self.id = id - self.in_response_to = in_response_to - self.version = version - self.issue_instant = issue_instant - self.destination = destination - self.consent = consent - self.issuer = issuer - self.signature = signature - self.extensions = extensions - self.status = status - -def status_response_from_string(xml_string): - """ Create StatusResponse instance from an XML string """ - return create_class_from_xml_string(StatusResponse, xml_string) - - -# -------------------------------------------------------------------------- -# 3.3.1 AssertionIDRequest -# -------------------------------------------------------------------------- - -class AssertionIDRequest(AbstractRequest): - """The samlp:AssertionIDRequest element""" - - c_tag = 'AssertionIDRequest' - c_namespace = NAMESPACE - c_children = AbstractRequest.c_children.copy() - c_attributes = AbstractRequest.c_attributes.copy() - c_child_order = AbstractRequest.c_child_order[:] - c_attributes["AssertionIDRef"] = 'assertion_id_ref' - - def __init__(self, id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, - signature=None, extensions=None, - # new for this class - assertion_id_ref=None, - # ------------------ - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AssertionIDRequest - - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param assertion_id_ref: used to specify each assertion to return - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value - string pairs - """ - - AbstractRequest.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, text, extension_elements, - extension_attributes) - - self.assertion_id_ref = assertion_id_ref - -def assertion_id_request_from_string(xml_string): - """ Create AssertionIDRequest instance from an XML string """ - return create_class_from_xml_string(AssertionIDRequest, xml_string) - -# -------------------------------------------------------------------------- -# 3.3.2.1 SubjectQuery -# -------------------------------------------------------------------------- - -class SubjectQuery(AbstractRequest): - """The samlp:SubjectQuery element""" - - c_tag = 'SubjectQuery' - c_namespace = NAMESPACE - c_children = AbstractRequest.c_children.copy() - c_attributes = AbstractRequest.c_attributes.copy() - c_children['{%s}Subject' % saml.NAMESPACE] = ( - 'subject', saml.Subject) - c_child_order = AbstractRequest.c_child_order[:] - c_child_order.append("subject") - - def __init__(self, id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, - signature=None, extensions=None, - #------------ - subject=None, - #------------ - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for SubjectQuery - - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param subject: The subject looked for - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value - string pairs - """ - - AbstractRequest.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, text, extension_elements, - extension_attributes) - - self.subject = subject - -def subject_query_from_string(xml_string): - """ Create SubjectQuery instance from an XML string """ - return create_class_from_xml_string(SubjectQuery, xml_string) - -# ---------------------------------------------------------------------- -# SessionIndex -# ---------------------------------------------------------------------- - -class SessionIndex(SamlBase): - """The samlp:SessionIndex element""" - c_tag = 'SessionIndex' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - -def session_index_from_string(xml_string): - """ Create SessionIndex instance from an XML string """ - return create_class_from_xml_string(SessionIndex, xml_string) - -# -------------------------------------------------------------------------- -# AuthnQuery -# -------------------------------------------------------------------------- - -class AuthnQuery(SubjectQuery): - """The samlp:AuthnQuery element""" - - c_tag = 'SubjectQuery' - c_namespace = NAMESPACE - c_children = SubjectQuery.c_children.copy() - c_attributes = SubjectQuery.c_attributes.copy() - c_attributes['SessionIndex'] = 'session_index' - - def __init__(self, id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, signature=None, - extensions=None, subject=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for SubjectQuery - - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param subject: The subject looked for - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value - string pairs - """ - - SubjectQuery.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, text, extension_elements, - extension_attributes) - - self.subject = subject - -def authn_query_from_string(xml_string): - """ Create AuthnQuery instance from an XML string """ - return create_class_from_xml_string(AuthnQuery, xml_string) - -# -------------------------------------------------------------------------- -# 3.3.2.2.1 RequestedAuthnContext -# -------------------------------------------------------------------------- - -class RequestedAuthnContext(SamlBase): - """The samlp:RequestedAuthnContext element""" - - c_tag = 'RequestedAuthnContext' - c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() - c_attributes['Comparison'] = 'comparison' - c_children['{%s}AuthnContextClassRef' % saml.NAMESPACE] = ( - 'authn_context_class_ref', [saml.AuthnContextClassRef]) - c_children['{%s}AuthnContextDeclRef' % saml.NAMESPACE] = ( - 'authn_context_decl_ref', [saml.AuthnContextDeclRef]) - - def __init__(self, comparison=None, authn_context_class_ref=None, - authn_context_decl_ref=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for RequestedAuthnContext - - :param comparison: Comparison attribute - :param authn_context_class_ref: list A list of AuthnContextClassRef - instances - :param authn_context_decl_ref: list A list of AuthnContextDeclRef - instances - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ('authn_context_class_ref', [saml.AuthnContextClassRef]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ('authn_context_decl_ref', [saml.AuthnContextDeclRef]) + c_attributes['Comparison'] = ('comparison', 'AuthnContextComparisonType', False) + c_child_order.extend(['authn_context_class_ref', 'authn_context_decl_ref']) + def __init__(self, + authn_context_class_ref=None, + authn_context_decl_ref=None, + comparison=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): SamlBase.__init__(self, - text, extension_elements, extension_attributes) - self.comparison = comparison - self.authn_context_class_ref = authn_context_class_ref or [] - self.authn_context_decl_ref = authn_context_decl_ref or [] + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.authn_context_class_ref=authn_context_class_ref or [] + self.authn_context_decl_ref=authn_context_decl_ref or [] + self.comparison=comparison -def requested_authn_context_from_string(xml_string): - """ Create RequestedAuthnContext instance from an XML string """ - return create_class_from_xml_string(RequestedAuthnContext, xml_string) +def requested_authn_context_type_from_string(xml_string): + return saml2.create_class_from_xml_string(RequestedAuthnContextType, xml_string) -# -------------------------------------------------------------------------- -# 3.3.2.3 AttributeQuery -# -------------------------------------------------------------------------- +class AuthnContextComparisonType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:AuthnContextComparisonType element """ -class AttributeQuery(SubjectQuery): - """The samlp:AttributeQuery element""" - - c_tag = 'AttributeQuery' + c_tag = 'AuthnContextComparisonType' c_namespace = NAMESPACE - c_children = SubjectQuery.c_children.copy() - c_attributes = SubjectQuery.c_attributes.copy() - c_child_order = SubjectQuery.c_child_order[:] - c_children['{%s}Attribute' % saml.NAMESPACE] = ( - 'attribute', [saml.Attribute]) - c_child_order.append("attribute") - - def __init__(self, id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, signature=None, - extensions=None, subject=None, - #-------------- - attribute=None, - #-------------- - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AttributeQuery - - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param subject: The subject looked for - :param attribute: If present in the query, they constrain/filter the - attributes and optionally the values returned. - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value - string pairs - """ - - SubjectQuery.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, subject, - text, extension_elements, extension_attributes) - - self.attribute = attribute - -def attribute_query_from_string(xml_string): - """ Create AttributeQuery instance from an XML string """ - return create_class_from_xml_string(AttributeQuery, xml_string) - -# -------------------------------------------------------------------------- - -class Resource(SamlBase): - """The saml:Resource element""" - - c_tag = 'Resource' - c_namespace = saml.NAMESPACE + c_value_type = {'base': 'string', 'enumeration': ['exact', 'minimum', 'maximum', 'better']} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def resource_from_string(xml_string): - """ Create Resource instance from an XML string """ - return create_class_from_xml_string(Resource, xml_string) +def authn_context_comparison_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnContextComparisonType, xml_string) -# -------------------------------------------------------------------------- -# 3.3.2.4 AuthzDecisionQuery -# -------------------------------------------------------------------------- +class NameIDPolicyType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:NameIDPolicyType element """ -class AuthzDecisionQuery(SubjectQuery): - """The samlp:AuthzDecisionQuery element""" - - c_tag = 'AuthzDecisionQuery' - c_namespace = NAMESPACE - c_children = SubjectQuery.c_children.copy() - c_attributes = SubjectQuery.c_attributes.copy() - c_children['{%s}Resource' % saml.NAMESPACE] = ( - 'resource', Resource) - c_children['{%s}Action' % saml.NAMESPACE] = ( - 'action', [saml.Action]) - c_children['{%s}Evidence' % saml.NAMESPACE] = ( - 'evidence', saml.Evidence) - c_child_order = SubjectQuery.c_child_order[:] - c_child_order.extend(['action', 'evidence', 'resource']) - - def __init__(self, id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, signature=None, - extensions=None, subject=None, resource=None, - action=None, evidence=None, - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AuthzDecisionQuery - - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param subject: The subject looked for - :param resource: A URI reference indicating the resource for which - authorization is requested. - :param action: If present in the query, they constrain/filter the - attributes and optionally the values returned. - :param evidence: - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value - string pairs - """ - - SubjectQuery.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, subject, text, extension_elements, - extension_attributes) - - self.resource = resource - self.action = action or [] - self.evidence = evidence - -def authz_decision_query_from_string(xml_string): - """ Create AuthzDecisionQuery instance from an XML string """ - return create_class_from_xml_string(AuthzDecisionQuery, xml_string) - -# ========================================================================== -# 3.3.3 Response -# ========================================================================== - -class Response(StatusResponse): - """The samlp:Response element""" - - c_tag = 'Response' - c_namespace = NAMESPACE - c_children = StatusResponse.c_children.copy() - c_attributes = StatusResponse.c_attributes.copy() - c_children['{%s}Assertion' % saml.NAMESPACE] = ( - 'assertion', [saml.Assertion]) - c_children['{%s}EncryptedAssertion' % saml.NAMESPACE] = ( - 'encrypted_assertion', [saml.EncryptedAssertion]) - c_child_order = StatusResponse.c_child_order[:] - c_child_order.extend(['assertion', 'encrypted_assertion']) - - def __init__(self, id=None, in_response_to=None, version=None, - issue_instant=None, destination=None, consent=None, - issuer=None, signature=None, extensions=None, status=None, - assertion=None, encrypted_assertion=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for Response - - :param id: ID attribute - :param in_respones_to: InResponseTo attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param status: Status element - :param assertion: Assertion elements - :param encrypted_assertion: EncryptedAssertion elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - StatusResponse.__init__(self, id, in_response_to, - version, issue_instant, - destination, consent, - issuer, signature, - extensions, status, text, - extension_elements, extension_attributes) - self.assertion = assertion or [] - self.encrypted_assertion = encrypted_assertion or [] - -def response_from_string(xml_string): - """ Create Response instance from an XML string """ - return create_class_from_xml_string(Response, xml_string) - -# -------------------------------------------------------------------------- -# 3.4.1.1 NameIDPolicy -# -------------------------------------------------------------------------- - -class NameIDPolicy(SamlBase): - """The samlp:NameIDPolicy element""" - - c_tag = 'NameIDPolicy' + c_tag = 'NameIDPolicyType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['Format'] = 'format' - c_attributes['SPNameQualifier'] = 'sp_name_qualifier' - c_attributes['AllowCreate'] = 'allow_create' + c_child_order = SamlBase.c_child_order[:] + c_attributes['Format'] = ('format', 'anyURI', False) + c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) + c_attributes['AllowCreate'] = ('allow_create', 'boolean', False) - def __init__(self, format=None, sp_name_qualifier=None, allow_create=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for NameIDPolicy + def __init__(self, + format=None, + sp_name_qualifier=None, + allow_create=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.format=format + self.sp_name_qualifier=sp_name_qualifier + self.allow_create=allow_create - :param format: Format attribute - :param sp_name_qualifier: SPNameQualifier attribute - :param allow_create: AllowCreate attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.format = format - self.sp_name_qualifier = sp_name_qualifier - self.allow_create = allow_create - -def name_id_policy_from_string(xml_string): - """ Create NameIDPolicy instance from an XML string """ - return create_class_from_xml_string(NameIDPolicy, xml_string) - -# -------------------------------------------------------------------------- +def name_id_policy_type_from_string(xml_string): + return saml2.create_class_from_xml_string(NameIDPolicyType, xml_string) class RequesterID(SamlBase): - """The samlp:RequesterID element""" + """The urn:oasis:names:tc:SAML:2.0:protocol:RequesterID element """ + c_tag = 'RequesterID' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def requester_id_from_string(xml_string): - """ Create RequesterID instance from an XML string """ - return create_class_from_xml_string(RequesterID, xml_string) + return saml2.create_class_from_xml_string(RequesterID, xml_string) -# -------------------------------------------------------------------------- -# 3.4.1.2 IDPEntry -# -------------------------------------------------------------------------- +class IDPEntryType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:IDPEntryType element """ -class IDPEntry(SamlBase): - """The samlp:IDPEntry element""" - - c_tag = 'IDPEntry' + c_tag = 'IDPEntryType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['ProviderID'] = 'provider_id' - c_attributes['Name'] = 'name' - c_attributes['Loc'] = 'loc' + c_child_order = SamlBase.c_child_order[:] + c_attributes['ProviderID'] = ('provider_id', 'anyURI', True) + c_attributes['Name'] = ('name', 'string', False) + c_attributes['Loc'] = ('loc', 'anyURI', False) - def __init__(self, provider_id=None, name=None, loc=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for IDPEntry + def __init__(self, + provider_id=None, + name=None, + loc=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.provider_id=provider_id + self.name=name + self.loc=loc - :param provider_id: ProviderID attribute - :param name: Name attribute - :param loc: Loc attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.provider_id = provider_id - self.name = name - self.loc = loc - -def idp_entry_from_string(xml_string): - """ Create IDPEntry instance from an XML string """ - return create_class_from_xml_string(IDPEntry, xml_string) - -# -------------------------------------------------------------------------- +def idp_entry_type_from_string(xml_string): + return saml2.create_class_from_xml_string(IDPEntryType, xml_string) class GetComplete(SamlBase): - """The samlp:GetComplete element""" + """The urn:oasis:names:tc:SAML:2.0:protocol:GetComplete element """ c_tag = 'GetComplete' c_namespace = NAMESPACE + c_value_type = 'anyURI' c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def get_complete_from_string(xml_string): - """ Create GetComplete instance from an XML string """ - return create_class_from_xml_string(GetComplete, xml_string) + return saml2.create_class_from_xml_string(GetComplete, xml_string) -# -------------------------------------------------------------------------- -# 3.4.1.2 IDPList -# -------------------------------------------------------------------------- +class Artifact(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:Artifact element """ -class IDPList(SamlBase): - """The samlp:IDPList element""" + c_tag = 'Artifact' + c_namespace = NAMESPACE + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - c_tag = 'IDPList' +def artifact_from_string(xml_string): + return saml2.create_class_from_xml_string(Artifact, xml_string) + +class NewID(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:NewID element """ + + c_tag = 'NewID' + c_namespace = NAMESPACE + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def new_id_from_string(xml_string): + return saml2.create_class_from_xml_string(NewID, xml_string) + +class NewEncryptedID(saml.EncryptedElementType): + """The urn:oasis:names:tc:SAML:2.0:protocol:NewEncryptedID element """ + + c_tag = 'NewEncryptedID' + c_namespace = NAMESPACE + c_children = saml.EncryptedElementType.c_children.copy() + c_attributes = saml.EncryptedElementType.c_attributes.copy() + c_child_order = saml.EncryptedElementType.c_child_order[:] + +def new_encrypted_id_from_string(xml_string): + return saml2.create_class_from_xml_string(NewEncryptedID, xml_string) + +class TerminateType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:TerminateType element """ + + c_tag = 'TerminateType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_children['{%s}IDPEntry' % NAMESPACE] = ('idp_entry', [IDPEntry]) - c_children['{%s}GetComplete' % NAMESPACE] = ( - 'get_complete', GetComplete) - c_child_order = ['idp_entry', 'get_complete'] + c_child_order = SamlBase.c_child_order[:] - def __init__(self, idp_entry=None, get_complete=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for IDPList +def terminate_type_from_string(xml_string): + return saml2.create_class_from_xml_string(TerminateType, xml_string) - :param idp_entry: IDPEntry elements - :param get_complete: GetComplete element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +class SessionIndex(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:SessionIndex element """ - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.idp_entry = idp_entry or [] - self.get_complete = get_complete + c_tag = 'SessionIndex' + c_namespace = NAMESPACE + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def idp_list_from_string(xml_string): - """ Create IDPList instance from an XML string """ - return create_class_from_xml_string(IDPList, xml_string) +def session_index_from_string(xml_string): + return saml2.create_class_from_xml_string(SessionIndex, xml_string) -# -------------------------------------------------------------------------- -# 3.4.1.2 Scoping -# -------------------------------------------------------------------------- +class Extensions(ExtensionsType): + """The urn:oasis:names:tc:SAML:2.0:protocol:Extensions element """ -class Scoping(SamlBase): - """The samlp:Scoping element""" + c_tag = 'Extensions' + c_namespace = NAMESPACE + c_children = ExtensionsType.c_children.copy() + c_attributes = ExtensionsType.c_attributes.copy() + c_child_order = ExtensionsType.c_child_order[:] - c_tag = 'Scoping' +def extensions_from_string(xml_string): + return saml2.create_class_from_xml_string(Extensions, xml_string) + +class StatusDetail(StatusDetailType): + """The urn:oasis:names:tc:SAML:2.0:protocol:StatusDetail element """ + + c_tag = 'StatusDetail' + c_namespace = NAMESPACE + c_children = StatusDetailType.c_children.copy() + c_attributes = StatusDetailType.c_attributes.copy() + c_child_order = StatusDetailType.c_child_order[:] + +def status_detail_from_string(xml_string): + return saml2.create_class_from_xml_string(StatusDetail, xml_string) + +class RequestAbstractType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:RequestAbstractType element """ + + c_tag = 'RequestAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() - c_attributes['ProxyCount'] = 'proxy_count' - c_children['{%s}IDPList' % NAMESPACE] = ('idp_list', IDPList) - c_children['{%s}RequesterID' % NAMESPACE] = ( - 'requester_id', [RequesterID]) - c_child_order = ['idp_list', 'requester_id'] + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', saml.Issuer) + c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}Extensions'] = ('extensions', Extensions) + c_attributes['ID'] = ('id', 'ID', True) + c_attributes['Version'] = ('version', 'string', True) + c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True) + c_attributes['Destination'] = ('destination', 'anyURI', False) + c_attributes['Consent'] = ('consent', 'anyURI', False) + c_child_order.extend(['issuer', 'signature', 'extensions']) - def __init__(self, proxy_count=None, idp_list=None, requester_id=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for Scoping + def __init__(self, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.issuer=issuer + self.signature=signature + self.extensions=extensions + self.id=id + self.version=version + self.issue_instant=issue_instant + self.destination=destination + self.consent=consent - :param proxy_count: ProxyCount attribute - :param idp_list: IDPList element - :param requester_id: list A list of RequesterID instances - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +def request_abstract_type_from_string(xml_string): + return saml2.create_class_from_xml_string(RequestAbstractType, xml_string) - SamlBase.__init__(self, text, extension_elements, extension_attributes) - self.proxy_count = proxy_count - self.idp_list = idp_list - self.requester_id = requester_id or [] +class AssertionIDRequestType(RequestAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AssertionIDRequestType element """ -def scoping_from_string(xml_string): - """ Create Scoping instance from an XML string """ - return create_class_from_xml_string(Scoping, xml_string) - - -# ====================================================================== -# 3.4 Authentication Request Protocol -# ====================================================================== - -class AuthnRequest(AbstractRequest): - """The samlp:AuthnRequest element""" - - c_tag = 'AuthnRequest' + c_tag = 'AssertionIDRequestType' c_namespace = NAMESPACE - c_children = AbstractRequest.c_children.copy() - c_attributes = AbstractRequest.c_attributes.copy() - c_attributes['ForceAuthn'] = 'force_authn' - c_attributes['IsPassive'] = 'is_passive' - c_attributes['AssertionConsumerServiceIndex'] = \ - 'assertion_consumer_service_index' - c_attributes['AssertionConsumerServiceURL'] = \ - 'assertion_consumer_service_url' - c_attributes['ProtocolBinding'] = 'protocol_binding' - c_attributes['AssertionConsumingServiceIndex'] = \ - 'assertion_consuming_service_index' - c_attributes['ProviderName'] = 'provider_name' - c_children['{%s}Subject' % saml.NAMESPACE] = ('subject', saml.Subject) - c_children['{%s}NameIDPolicy' % NAMESPACE] = ( - 'name_id_policy', NameIDPolicy) - c_children['{%s}Conditions' % saml.NAMESPACE] = ( - 'conditions', saml.Conditions) - c_children['{%s}RequestedAuthnContext' % NAMESPACE] = ( - 'requested_authn_context', RequestedAuthnContext) - c_children['{%s}Scoping' % NAMESPACE] = ('scoping', Scoping) + c_children = RequestAbstractType.c_children.copy() + c_attributes = RequestAbstractType.c_attributes.copy() + c_child_order = RequestAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ('assertion_id_ref', [saml.AssertionIDRef]) + c_child_order.extend(['assertion_id_ref']) - c_child_order = AbstractRequest.c_child_order[:] - c_child_order.extend(['subject', 'name_id_policy', 'conditions', - 'requested_authn_context', 'scoping']) + def __init__(self, + assertion_id_ref=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RequestAbstractType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.assertion_id_ref=assertion_id_ref or [] - def __init__(self, id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, signature=None, - extensions=None, - # ------------------------------ - subject=None, name_id_policy=None, - conditions=None, requested_authn_context=None, scoping=None, - force_authn=None, is_passive=None, - assertion_consumer_service_index=None, - assertion_consumer_service_url=None, - protocol_binding=None, assertion_consuming_service_index=None, - provider_name=None, - # ------------------------------ - text=None, extension_elements=None, - extension_attributes=None): - """Constructor for AuthnRequest +def assertion_id_request_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AssertionIDRequestType, xml_string) - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param subject: Subject element - :param name_id_policy: NameIDPolicy element - :param conditions: Conditions element - :param requested_authn_context: RequestedAuthnContext element - :param scoping: Scoping element - :param force_authn: ForceAuthn attribute - :param is_passive: IsPassive attribute - :param assertion_consumer_service_index: AssertionConsumerServiceIndex - element - :param assertion_consumer_service_url: AssertionConsumerServiceURL - element - :param protocol_binding: ProtocolBinding element - :param assertion_consuming_service_index: - AssertionConsumingServiceIndex element - :param provider_name: ProviderName element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - AbstractRequest.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, text, extension_elements, - extension_attributes) - self.subject = subject - self.name_id_policy = name_id_policy - self.conditions = conditions - self.requested_authn_context = requested_authn_context - self.scoping = scoping - self.force_authn = force_authn - self.is_passive = is_passive - self.assertion_consumer_service_index = \ - assertion_consumer_service_index - self.assertion_consumer_service_url = assertion_consumer_service_url - self.protocol_binding = protocol_binding - self.assertion_consuming_service_index = \ - assertion_consuming_service_index - self.provider_name = provider_name +class SubjectQueryAbstractType(RequestAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:SubjectQueryAbstractType element """ -def authn_request_from_string(xml_string): - """ Create AuthnRequest instance from an XML string """ - return create_class_from_xml_string(AuthnRequest, xml_string) + c_tag = 'SubjectQueryAbstractType' + c_namespace = NAMESPACE + c_children = RequestAbstractType.c_children.copy() + c_attributes = RequestAbstractType.c_attributes.copy() + c_child_order = RequestAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', saml.Subject) + c_child_order.extend(['subject']) + def __init__(self, + subject=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RequestAbstractType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.subject=subject -# ---------------------------------------------------------------------- -# 3.5.1 ArtifactResolve -# ---------------------------------------------------------------------- +def subject_query_abstract_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectQueryAbstractType, xml_string) -# ---------------------------------------------------------------------- -# 3.5.2 ArtifactResponse -# ---------------------------------------------------------------------- +class RequestedAuthnContext(RequestedAuthnContextType): + """The urn:oasis:names:tc:SAML:2.0:protocol:RequestedAuthnContext element """ -# ...................................................................... + c_tag = 'RequestedAuthnContext' + c_namespace = NAMESPACE + c_children = RequestedAuthnContextType.c_children.copy() + c_attributes = RequestedAuthnContextType.c_attributes.copy() + c_child_order = RequestedAuthnContextType.c_child_order[:] -class Terminate(SamlBase): - """The samlp:Terminate element""" +def requested_authn_context_from_string(xml_string): + return saml2.create_class_from_xml_string(RequestedAuthnContext, xml_string) + +class AttributeQueryType(SubjectQueryAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AttributeQueryType element """ + + c_tag = 'AttributeQueryType' + c_namespace = NAMESPACE + c_children = SubjectQueryAbstractType.c_children.copy() + c_attributes = SubjectQueryAbstractType.c_attributes.copy() + c_child_order = SubjectQueryAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ('attribute', [saml.Attribute]) + c_child_order.extend(['attribute']) + + def __init__(self, + attribute=None, + subject=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SubjectQueryAbstractType.__init__(self, + subject=subject, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.attribute=attribute or [] + +def attribute_query_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeQueryType, xml_string) + +class AuthzDecisionQueryType(SubjectQueryAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AuthzDecisionQueryType element """ + + c_tag = 'AuthzDecisionQueryType' + c_namespace = NAMESPACE + c_children = SubjectQueryAbstractType.c_children.copy() + c_attributes = SubjectQueryAbstractType.c_attributes.copy() + c_child_order = SubjectQueryAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ('action', [saml.Action]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ('evidence', saml.Evidence) + c_attributes['Resource'] = ('resource', 'anyURI', True) + c_child_order.extend(['action', 'evidence']) + + def __init__(self, + action=None, + evidence=None, + resource=None, + subject=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SubjectQueryAbstractType.__init__(self, + subject=subject, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.action=action or [] + self.evidence=evidence + self.resource=resource + +def authz_decision_query_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthzDecisionQueryType, xml_string) + +class NameIDPolicy(NameIDPolicyType): + """The urn:oasis:names:tc:SAML:2.0:protocol:NameIDPolicy element """ + + c_tag = 'NameIDPolicy' + c_namespace = NAMESPACE + c_children = NameIDPolicyType.c_children.copy() + c_attributes = NameIDPolicyType.c_attributes.copy() + c_child_order = NameIDPolicyType.c_child_order[:] + +def name_id_policy_from_string(xml_string): + return saml2.create_class_from_xml_string(NameIDPolicy, xml_string) + +class IDPEntry(IDPEntryType): + """The urn:oasis:names:tc:SAML:2.0:protocol:IDPEntry element """ + + c_tag = 'IDPEntry' + c_namespace = NAMESPACE + c_children = IDPEntryType.c_children.copy() + c_attributes = IDPEntryType.c_attributes.copy() + c_child_order = IDPEntryType.c_child_order[:] + +def idp_entry_from_string(xml_string): + return saml2.create_class_from_xml_string(IDPEntry, xml_string) + +class ArtifactResolveType(RequestAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:ArtifactResolveType element """ + + c_tag = 'ArtifactResolveType' + c_namespace = NAMESPACE + c_children = RequestAbstractType.c_children.copy() + c_attributes = RequestAbstractType.c_attributes.copy() + c_child_order = RequestAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}Artifact'] = ('artifact', Artifact) + c_child_order.extend(['artifact']) + + def __init__(self, + artifact=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RequestAbstractType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.artifact=artifact + +def artifact_resolve_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ArtifactResolveType, xml_string) + +class Terminate(TerminateType): + """The urn:oasis:names:tc:SAML:2.0:protocol:Terminate element """ c_tag = 'Terminate' c_namespace = NAMESPACE - c_children = SamlBase.c_children.copy() - c_attributes = SamlBase.c_attributes.copy() + c_children = TerminateType.c_children.copy() + c_attributes = TerminateType.c_attributes.copy() + c_child_order = TerminateType.c_child_order[:] def terminate_from_string(xml_string): - """ Create Terminate instance from an XML string """ - return create_class_from_xml_string(Terminate, xml_string) - -# ---------------------------------------------------------------------- -# 3.6.1 ManageNameIDRequest -# ---------------------------------------------------------------------- + return saml2.create_class_from_xml_string(Terminate, xml_string) -class ManageNameIDRequest(AbstractRequest): - """The samlp:NameIDMappingRequest element - To request an alternate name id for a principal from an identity - provider, a requester sends an NameIDMappingRequest message - """ +class LogoutRequestType(RequestAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:LogoutRequestType element """ - c_tag = 'ManageNameIDRequest' + c_tag = 'LogoutRequestType' c_namespace = NAMESPACE - c_children = AbstractRequest.c_children.copy() - c_attributes = AbstractRequest.c_attributes.copy() - c_attributes["NewID"] = "new_id" - c_children['{%s}NameID' % saml.NAMESPACE] = ('name_id', saml.NameID) - c_children['{%s}EncryptedID' % saml.NAMESPACE] = ( - 'encrypted_id', saml.EncryptedID) - c_children['{%s}NewEncryptedID' % saml.NAMESPACE] = ( - 'new_encrypted_id', saml.EncryptedID) - c_children['{%s}Terminate' % NAMESPACE] = ( - 'terminate', Terminate) - c_child_order = AbstractRequest.c_child_order[:] - c_child_order.extend(['name_id', 'encrypted_id', - 'new_id', 'new_encrypted_id', 'terminate']) + c_children = RequestAbstractType.c_children.copy() + c_attributes = RequestAbstractType.c_attributes.copy() + c_child_order = RequestAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', saml.BaseID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', saml.NameID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ('encrypted_id', saml.EncryptedID) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}SessionIndex'] = ('session_index', [SessionIndex]) + c_attributes['Reason'] = ('reason', 'string', False) + c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) + c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'session_index']) - def __init__(self, new_id=None, name_id=None, encrypted_id=None, - new_encrypted_id=None, terminate=None, - id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, signature=None, - extensions=None, name_id_policy=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for ManageNameIDRequest + def __init__(self, + base_id=None, + name_id=None, + encrypted_id=None, + session_index=None, + reason=None, + not_on_or_after=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RequestAbstractType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.base_id=base_id + self.name_id=name_id + self.encrypted_id=encrypted_id + self.session_index=session_index or [] + self.reason=reason + self.not_on_or_after=not_on_or_after - :param new_id: The new id value - :param name_id: NameID element - :param encrypted_id: EncryptedID element - :param new_encrypted_id: - :param terminate: +def logout_request_type_from_string(xml_string): + return saml2.create_class_from_xml_string(LogoutRequestType, xml_string) - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - AbstractRequest.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, text, extension_elements, - extension_attributes) - self.new_id = new_id - self.name_id = name_id - self.encrypted_id = encrypted_id - self.new_encrypted_id = new_encrypted_id - self.terminate = terminate +class NameIDMappingRequestType(RequestAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:NameIDMappingRequestType element """ -def manage_name_id_request_from_string(xml_string): - """ Create ManageNameIDRequest instance from an XML string """ - return create_class_from_xml_string(ManageNameIDRequest, xml_string) - - -# ---------------------------------------------------------------------- -# 3.6.2 ManageNameIDResponse -# ---------------------------------------------------------------------- - -class ManageNameIDResponse(StatusResponse): - """The samlp:ManageNameIDResponse element""" - - c_tag = 'ManageNameIDResponse' + c_tag = 'NameIDMappingRequestType' c_namespace = NAMESPACE - c_children = StatusResponse.c_children.copy() - c_attributes = StatusResponse.c_attributes.copy() + c_children = RequestAbstractType.c_children.copy() + c_attributes = RequestAbstractType.c_attributes.copy() + c_child_order = RequestAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', saml.BaseID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', saml.NameID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ('encrypted_id', saml.EncryptedID) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}NameIDPolicy'] = ('name_id_policy', NameIDPolicy) + c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'name_id_policy']) -def manage_name_id_response_from_string(xml_string): - """ Create ManageNameIDResponse instance from an XML string """ - return create_class_from_xml_string(ManageNameIDResponse, xml_string) + def __init__(self, + base_id=None, + name_id=None, + encrypted_id=None, + name_id_policy=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RequestAbstractType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.base_id=base_id + self.name_id=name_id + self.encrypted_id=encrypted_id + self.name_id_policy=name_id_policy +def name_id_mapping_request_type_from_string(xml_string): + return saml2.create_class_from_xml_string(NameIDMappingRequestType, xml_string) -# ---------------------------------------------------------------------- -# 3.7.1 LogoutRequest -# ---------------------------------------------------------------------- +class AssertionIDRequest(AssertionIDRequestType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AssertionIDRequest element """ -class LogoutRequest(AbstractRequest): - """The samlp:LogoutRequest element""" + c_tag = 'AssertionIDRequest' + c_namespace = NAMESPACE + c_children = AssertionIDRequestType.c_children.copy() + c_attributes = AssertionIDRequestType.c_attributes.copy() + c_child_order = AssertionIDRequestType.c_child_order[:] + +def assertion_id_request_from_string(xml_string): + return saml2.create_class_from_xml_string(AssertionIDRequest, xml_string) + +class SubjectQuery(SubjectQueryAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:SubjectQuery element """ + + c_tag = 'SubjectQuery' + c_namespace = NAMESPACE + c_children = SubjectQueryAbstractType.c_children.copy() + c_attributes = SubjectQueryAbstractType.c_attributes.copy() + c_child_order = SubjectQueryAbstractType.c_child_order[:] + +def subject_query_from_string(xml_string): + return saml2.create_class_from_xml_string(SubjectQuery, xml_string) + +class AuthnQueryType(SubjectQueryAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AuthnQueryType element """ + + c_tag = 'AuthnQueryType' + c_namespace = NAMESPACE + c_children = SubjectQueryAbstractType.c_children.copy() + c_attributes = SubjectQueryAbstractType.c_attributes.copy() + c_child_order = SubjectQueryAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}RequestedAuthnContext'] = ('requested_authn_context', RequestedAuthnContext) + c_attributes['SessionIndex'] = ('session_index', 'string', False) + c_child_order.extend(['requested_authn_context']) + + def __init__(self, + requested_authn_context=None, + session_index=None, + subject=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SubjectQueryAbstractType.__init__(self, + subject=subject, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.requested_authn_context=requested_authn_context + self.session_index=session_index + +def authn_query_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnQueryType, xml_string) + +class AttributeQuery(AttributeQueryType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AttributeQuery element """ + + c_tag = 'AttributeQuery' + c_namespace = NAMESPACE + c_children = AttributeQueryType.c_children.copy() + c_attributes = AttributeQueryType.c_attributes.copy() + c_child_order = AttributeQueryType.c_child_order[:] + +def attribute_query_from_string(xml_string): + return saml2.create_class_from_xml_string(AttributeQuery, xml_string) + +class AuthzDecisionQuery(AuthzDecisionQueryType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AuthzDecisionQuery element """ + + c_tag = 'AuthzDecisionQuery' + c_namespace = NAMESPACE + c_children = AuthzDecisionQueryType.c_children.copy() + c_attributes = AuthzDecisionQueryType.c_attributes.copy() + c_child_order = AuthzDecisionQueryType.c_child_order[:] + +def authz_decision_query_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthzDecisionQuery, xml_string) + +class IDPListType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:IDPListType element """ + + c_tag = 'IDPListType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}IDPEntry'] = ('idp_entry', [IDPEntry]) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}GetComplete'] = ('get_complete', GetComplete) + c_child_order.extend(['idp_entry', 'get_complete']) + + def __init__(self, + idp_entry=None, + get_complete=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.idp_entry=idp_entry or [] + self.get_complete=get_complete + +def idp_list_type_from_string(xml_string): + return saml2.create_class_from_xml_string(IDPListType, xml_string) + +class ArtifactResolve(ArtifactResolveType): + """The urn:oasis:names:tc:SAML:2.0:protocol:ArtifactResolve element """ + + c_tag = 'ArtifactResolve' + c_namespace = NAMESPACE + c_children = ArtifactResolveType.c_children.copy() + c_attributes = ArtifactResolveType.c_attributes.copy() + c_child_order = ArtifactResolveType.c_child_order[:] + +def artifact_resolve_from_string(xml_string): + return saml2.create_class_from_xml_string(ArtifactResolve, xml_string) + +class ManageNameIDRequestType(RequestAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:ManageNameIDRequestType element """ + + c_tag = 'ManageNameIDRequestType' + c_namespace = NAMESPACE + c_children = RequestAbstractType.c_children.copy() + c_attributes = RequestAbstractType.c_attributes.copy() + c_child_order = RequestAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', saml.NameID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ('encrypted_id', saml.EncryptedID) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}NewID'] = ('new_id', NewID) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}NewEncryptedID'] = ('new_encrypted_id', NewEncryptedID) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}Terminate'] = ('terminate', Terminate) + c_child_order.extend(['name_id', 'encrypted_id', 'new_id', 'new_encrypted_id', 'terminate']) + + def __init__(self, + name_id=None, + encrypted_id=None, + new_id=None, + new_encrypted_id=None, + terminate=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RequestAbstractType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.name_id=name_id + self.encrypted_id=encrypted_id + self.new_id=new_id + self.new_encrypted_id=new_encrypted_id + self.terminate=terminate + +def manage_name_id_request_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ManageNameIDRequestType, xml_string) + +class LogoutRequest(LogoutRequestType): + """The urn:oasis:names:tc:SAML:2.0:protocol:LogoutRequest element """ c_tag = 'LogoutRequest' c_namespace = NAMESPACE - c_children = AbstractRequest.c_children.copy() - c_attributes = AbstractRequest.c_attributes.copy() - c_attributes['NotOnOrAfter'] = 'not_on_or_after' - c_attributes['Reason'] = 'reason' - c_children['{%s}BaseID' % saml.NAMESPACE] = ('base_id', saml.BaseID) - c_children['{%s}NameID' % saml.NAMESPACE] = ('name_id', saml.NameID) - c_children['{%s}EncryptedID' % saml.NAMESPACE] = ( - 'encrypted_id', saml.EncryptedID) - c_children['{%s}SessionIndex' % NAMESPACE] = ( - 'session_index', SessionIndex) - c_child_order = AbstractRequest.c_child_order[:] - c_child_order.extend(['issuer', 'signature', 'extensions', 'base_id', - 'name_id', 'encrypted_id', 'session_index']) - - def __init__(self, id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, signature=None, - extensions=None, not_on_or_after=None, reason=None, - base_id=None, name_id=None, encrypted_id=None, - session_index=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for LogoutRequest - - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param not_on_or_after: NotOnOrAfter attribute - :param reason: Reason attribute - :param base_id: BaseID element - :param name_id: NameID element - :param encrypted_id: EncryptedID element - :param session_index: SessionIndex element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - AbstractRequest.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, text, extension_elements, - extension_attributes) - self.not_on_or_after = not_on_or_after - self.reason = reason - self.base_id = base_id - self.name_id = name_id - self.encrypted_id = encrypted_id - self.session_index = session_index + c_children = LogoutRequestType.c_children.copy() + c_attributes = LogoutRequestType.c_attributes.copy() + c_child_order = LogoutRequestType.c_child_order[:] def logout_request_from_string(xml_string): - """ Create LogoutRequest instance from an XML string """ - return create_class_from_xml_string(LogoutRequest, xml_string) + return saml2.create_class_from_xml_string(LogoutRequest, xml_string) - -# ---------------------------------------------------------------------- -# 3.7.2 LogoutResponse -# ---------------------------------------------------------------------- - -class LogoutResponse(StatusResponse): - """The samlp:LogoutResponse element""" - - c_tag = 'LogoutResponse' - c_namespace = NAMESPACE - c_children = StatusResponse.c_children.copy() - c_attributes = StatusResponse.c_attributes.copy() - -def logout_response_from_string(xml_string): - """ Create LogoutResponse instance from an XML string """ - return create_class_from_xml_string(LogoutResponse, xml_string) - -# ---------------------------------------------------------------------- -# 3.8.1 NameIDMappingRequest -# ---------------------------------------------------------------------- - -class NameIDMappingRequest(AbstractRequest): - """The samlp:NameIDMappingRequest element - To request an alternate name id for a principal from an identity - provider, a requester sends an NameIDMappingRequest message - """ +class NameIDMappingRequest(NameIDMappingRequestType): + """The urn:oasis:names:tc:SAML:2.0:protocol:NameIDMappingRequest element """ c_tag = 'NameIDMappingRequest' c_namespace = NAMESPACE - c_children = AbstractRequest.c_children.copy() - c_attributes = AbstractRequest.c_attributes.copy() - c_children['{%s}BaseID' % saml.NAMESPACE] = ('base_id', saml.BaseID) - c_children['{%s}NameID' % saml.NAMESPACE] = ('name_id', saml.NameID) - c_children['{%s}EncryptedID' % saml.NAMESPACE] = ( - 'encrypted_id', saml.EncryptedID) - c_children['{%s}NameIDPolicy' % NAMESPACE] = ( - 'name_id_policy', NameIDPolicy) - c_child_order = AbstractRequest.c_child_order[:] - c_child_order.extend(['base_id', 'name_id', 'encrypted_id', - 'name_id_policy']) - - def __init__(self, base_id=None, name_id=None, encrypted_id=None, - name_id_policy=None, - id=None, version=None, issue_instant=None, - destination=None, consent=None, issuer=None, signature=None, - extensions=None, - text=None, - extension_elements=None, extension_attributes=None): - """Constructor for LogoutRequest - - :param base_id: BaseID element - :param name_id: NameID element - :param encrypted_id: EncryptedID element - :param name_id_policy: The requirements regarding the format and - optional name qualifier for the id to be returned. - :param id: ID attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - AbstractRequest.__init__(self, id, version, issue_instant, - destination, consent, issuer, signature, - extensions, text, extension_elements, - extension_attributes) - self.base_id = base_id - self.name_id = name_id - self.encrypted_id = encrypted_id - self.name_id_policy = name_id_policy + c_children = NameIDMappingRequestType.c_children.copy() + c_attributes = NameIDMappingRequestType.c_attributes.copy() + c_child_order = NameIDMappingRequestType.c_child_order[:] def name_id_mapping_request_from_string(xml_string): - """ Create NameIDMappingRequest instance from an XML string """ - return create_class_from_xml_string(NameIDMappingRequest, xml_string) + return saml2.create_class_from_xml_string(NameIDMappingRequest, xml_string) +class AuthnQuery(AuthnQueryType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AuthnQuery element """ -# ---------------------------------------------------------------------- -# 3.8.1 NameIDMappingResponse -# ---------------------------------------------------------------------- + c_tag = 'AuthnQuery' + c_namespace = NAMESPACE + c_children = AuthnQueryType.c_children.copy() + c_attributes = AuthnQueryType.c_attributes.copy() + c_child_order = AuthnQueryType.c_child_order[:] -class NameIDMappingResponse(StatusResponse): - """The samlp:NameIDMappingResponse element""" +def authn_query_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnQuery, xml_string) + +class IDPList(IDPListType): + """The urn:oasis:names:tc:SAML:2.0:protocol:IDPList element """ + + c_tag = 'IDPList' + c_namespace = NAMESPACE + c_children = IDPListType.c_children.copy() + c_attributes = IDPListType.c_attributes.copy() + c_child_order = IDPListType.c_child_order[:] + +def idp_list_from_string(xml_string): + return saml2.create_class_from_xml_string(IDPList, xml_string) + +class ManageNameIDRequest(ManageNameIDRequestType): + """The urn:oasis:names:tc:SAML:2.0:protocol:ManageNameIDRequest element """ + + c_tag = 'ManageNameIDRequest' + c_namespace = NAMESPACE + c_children = ManageNameIDRequestType.c_children.copy() + c_attributes = ManageNameIDRequestType.c_attributes.copy() + c_child_order = ManageNameIDRequestType.c_child_order[:] + +def manage_name_id_request_from_string(xml_string): + return saml2.create_class_from_xml_string(ManageNameIDRequest, xml_string) + +class ScopingType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:ScopingType element """ + + c_tag = 'ScopingType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}IDPList'] = ('idp_list', IDPList) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}RequesterID'] = ('requester_id', [RequesterID]) + c_attributes['ProxyCount'] = ('proxy_count', 'nonNegativeInteger', False) + c_child_order.extend(['idp_list', 'requester_id']) + + def __init__(self, + idp_list=None, + requester_id=None, + proxy_count=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.idp_list=idp_list + self.requester_id=requester_id or [] + self.proxy_count=proxy_count + +def scoping_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ScopingType, xml_string) + +class Scoping(ScopingType): + """The urn:oasis:names:tc:SAML:2.0:protocol:Scoping element """ + + c_tag = 'Scoping' + c_namespace = NAMESPACE + c_children = ScopingType.c_children.copy() + c_attributes = ScopingType.c_attributes.copy() + c_child_order = ScopingType.c_child_order[:] + +def scoping_from_string(xml_string): + return saml2.create_class_from_xml_string(Scoping, xml_string) + +class AuthnRequestType(RequestAbstractType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AuthnRequestType element """ + + c_tag = 'AuthnRequestType' + c_namespace = NAMESPACE + c_children = RequestAbstractType.c_children.copy() + c_attributes = RequestAbstractType.c_attributes.copy() + c_child_order = RequestAbstractType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', saml.Subject) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}NameIDPolicy'] = ('name_id_policy', NameIDPolicy) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ('conditions', saml.Conditions) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}RequestedAuthnContext'] = ('requested_authn_context', RequestedAuthnContext) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}Scoping'] = ('scoping', Scoping) + c_attributes['ForceAuthn'] = ('force_authn', 'boolean', False) + c_attributes['IsPassive'] = ('is_passive', 'boolean', False) + c_attributes['ProtocolBinding'] = ('protocol_binding', 'anyURI', False) + c_attributes['AssertionConsumerServiceIndex'] = ('assertion_consumer_service_index', 'unsignedShort', False) + c_attributes['AssertionConsumerServiceURL'] = ('assertion_consumer_service_url', 'anyURI', False) + c_attributes['AttributeConsumingServiceIndex'] = ('attribute_consuming_service_index', 'unsignedShort', False) + c_attributes['ProviderName'] = ('provider_name', 'string', False) + c_child_order.extend(['subject', 'name_id_policy', 'conditions', 'requested_authn_context', 'scoping']) + + def __init__(self, + subject=None, + name_id_policy=None, + conditions=None, + requested_authn_context=None, + scoping=None, + force_authn=None, + is_passive=None, + protocol_binding=None, + assertion_consumer_service_index=None, + assertion_consumer_service_url=None, + attribute_consuming_service_index=None, + provider_name=None, + issuer=None, + signature=None, + extensions=None, + id=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + RequestAbstractType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + id=id, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.subject=subject + self.name_id_policy=name_id_policy + self.conditions=conditions + self.requested_authn_context=requested_authn_context + self.scoping=scoping + self.force_authn=force_authn + self.is_passive=is_passive + self.protocol_binding=protocol_binding + self.assertion_consumer_service_index=assertion_consumer_service_index + self.assertion_consumer_service_url=assertion_consumer_service_url + self.attribute_consuming_service_index=attribute_consuming_service_index + self.provider_name=provider_name + +def authn_request_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnRequestType, xml_string) + +class AuthnRequest(AuthnRequestType): + """The urn:oasis:names:tc:SAML:2.0:protocol:AuthnRequest element """ + + c_tag = 'AuthnRequest' + c_namespace = NAMESPACE + c_children = AuthnRequestType.c_children.copy() + c_attributes = AuthnRequestType.c_attributes.copy() + c_child_order = AuthnRequestType.c_child_order[:] + +def authn_request_from_string(xml_string): + return saml2.create_class_from_xml_string(AuthnRequest, xml_string) + +#.................. +# ['Status', 'StatusType', 'StatusCode', 'NameIDMappingResponseType', 'StatusCodeType', 'Response', 'ResponseType', 'LogoutResponse', 'ManageNameIDResponse', 'StatusResponseType', 'ArtifactResponse', 'ArtifactResponseType', 'NameIDMappingResponse'] +class StatusType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:StatusType element """ + + c_tag = 'StatusType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}StatusMessage'] = ('status_message', StatusMessage) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}StatusDetail'] = ('status_detail', StatusDetail) + c_child_order.extend(['status_code', 'status_message', 'status_detail']) + + def __init__(self, + status_code=None, + status_message=None, + status_detail=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.status_code=status_code + self.status_message=status_message + self.status_detail=status_detail + +def status_type_from_string(xml_string): + return saml2.create_class_from_xml_string(StatusType, xml_string) + +class Status(StatusType): + """The urn:oasis:names:tc:SAML:2.0:protocol:Status element """ + + c_tag = 'Status' + c_namespace = NAMESPACE + c_children = StatusType.c_children.copy() + c_attributes = StatusType.c_attributes.copy() + c_child_order = StatusType.c_child_order[:] + +def status_from_string(xml_string): + return saml2.create_class_from_xml_string(Status, xml_string) + +class StatusResponseType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:StatusResponseType element """ + + c_tag = 'StatusResponseType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', saml.Issuer) + c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}Extensions'] = ('extensions', Extensions) + c_children['{urn:oasis:names:tc:SAML:2.0:protocol}Status'] = ('status', Status) + c_attributes['ID'] = ('id', 'ID', True) + c_attributes['InResponseTo'] = ('in_response_to', 'NCName', False) + c_attributes['Version'] = ('version', 'string', True) + c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True) + c_attributes['Destination'] = ('destination', 'anyURI', False) + c_attributes['Consent'] = ('consent', 'anyURI', False) + c_child_order.extend(['issuer', 'signature', 'extensions', 'status']) + + def __init__(self, + issuer=None, + signature=None, + extensions=None, + status=None, + id=None, + in_response_to=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.issuer=issuer + self.signature=signature + self.extensions=extensions + self.status=status + self.id=id + self.in_response_to=in_response_to + self.version=version + self.issue_instant=issue_instant + self.destination=destination + self.consent=consent + +def status_response_type_from_string(xml_string): + return saml2.create_class_from_xml_string(StatusResponseType, xml_string) + +class ResponseType(StatusResponseType): + """The urn:oasis:names:tc:SAML:2.0:protocol:ResponseType element """ + + c_tag = 'ResponseType' + c_namespace = NAMESPACE + c_children = StatusResponseType.c_children.copy() + c_attributes = StatusResponseType.c_attributes.copy() + c_child_order = StatusResponseType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ('assertion', [saml.Assertion]) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ('encrypted_assertion', [saml.EncryptedAssertion]) + c_child_order.extend(['assertion', 'encrypted_assertion']) + + def __init__(self, + assertion=None, + encrypted_assertion=None, + issuer=None, + signature=None, + extensions=None, + status=None, + id=None, + in_response_to=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + StatusResponseType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + status=status, + id=id, + in_response_to=in_response_to, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.assertion=assertion or [] + self.encrypted_assertion=encrypted_assertion or [] + +def response_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ResponseType, xml_string) + +class ArtifactResponseType(StatusResponseType): + """The urn:oasis:names:tc:SAML:2.0:protocol:ArtifactResponseType element """ + + c_tag = 'ArtifactResponseType' + c_namespace = NAMESPACE + c_children = StatusResponseType.c_children.copy() + c_attributes = StatusResponseType.c_attributes.copy() + c_child_order = StatusResponseType.c_child_order[:] + +def artifact_response_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ArtifactResponseType, xml_string) + +class ManageNameIDResponse(StatusResponseType): + """The urn:oasis:names:tc:SAML:2.0:protocol:ManageNameIDResponse element """ + + c_tag = 'ManageNameIDResponse' + c_namespace = NAMESPACE + c_children = StatusResponseType.c_children.copy() + c_attributes = StatusResponseType.c_attributes.copy() + c_child_order = StatusResponseType.c_child_order[:] + +def manage_name_id_response_from_string(xml_string): + return saml2.create_class_from_xml_string(ManageNameIDResponse, xml_string) + +class LogoutResponse(StatusResponseType): + """The urn:oasis:names:tc:SAML:2.0:protocol:LogoutResponse element """ + + c_tag = 'LogoutResponse' + c_namespace = NAMESPACE + c_children = StatusResponseType.c_children.copy() + c_attributes = StatusResponseType.c_attributes.copy() + c_child_order = StatusResponseType.c_child_order[:] + +def logout_response_from_string(xml_string): + return saml2.create_class_from_xml_string(LogoutResponse, xml_string) + +class NameIDMappingResponseType(StatusResponseType): + """The urn:oasis:names:tc:SAML:2.0:protocol:NameIDMappingResponseType element """ + + c_tag = 'NameIDMappingResponseType' + c_namespace = NAMESPACE + c_children = StatusResponseType.c_children.copy() + c_attributes = StatusResponseType.c_attributes.copy() + c_child_order = StatusResponseType.c_child_order[:] + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', saml.NameID) + c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ('encrypted_id', saml.EncryptedID) + c_child_order.extend(['name_id', 'encrypted_id']) + + def __init__(self, + name_id=None, + encrypted_id=None, + issuer=None, + signature=None, + extensions=None, + status=None, + id=None, + in_response_to=None, + version=None, + issue_instant=None, + destination=None, + consent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + StatusResponseType.__init__(self, + issuer=issuer, + signature=signature, + extensions=extensions, + status=status, + id=id, + in_response_to=in_response_to, + version=version, + issue_instant=issue_instant, + destination=destination, + consent=consent, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.name_id=name_id + self.encrypted_id=encrypted_id + +def name_id_mapping_response_type_from_string(xml_string): + return saml2.create_class_from_xml_string(NameIDMappingResponseType, xml_string) + +class Response(ResponseType): + """The urn:oasis:names:tc:SAML:2.0:protocol:Response element """ + + c_tag = 'Response' + c_namespace = NAMESPACE + c_children = ResponseType.c_children.copy() + c_attributes = ResponseType.c_attributes.copy() + c_child_order = ResponseType.c_child_order[:] + +def response_from_string(xml_string): + return saml2.create_class_from_xml_string(Response, xml_string) + +class ArtifactResponse(ArtifactResponseType): + """The urn:oasis:names:tc:SAML:2.0:protocol:ArtifactResponse element """ + + c_tag = 'ArtifactResponse' + c_namespace = NAMESPACE + c_children = ArtifactResponseType.c_children.copy() + c_attributes = ArtifactResponseType.c_attributes.copy() + c_child_order = ArtifactResponseType.c_child_order[:] + +def artifact_response_from_string(xml_string): + return saml2.create_class_from_xml_string(ArtifactResponse, xml_string) + +class NameIDMappingResponse(NameIDMappingResponseType): + """The urn:oasis:names:tc:SAML:2.0:protocol:NameIDMappingResponse element """ c_tag = 'NameIDMappingResponse' c_namespace = NAMESPACE - c_children = StatusResponse.c_children.copy() - c_attributes = StatusResponse.c_attributes.copy() - c_children['{%s}NameID' % saml.NAMESPACE] = ( - 'name_id', saml.NameID) - c_children['{%s}EncryptedID' % saml.NAMESPACE] = ( - 'encrypted_id', saml.EncryptedID) - c_child_order = StatusResponse.c_child_order[:] - c_child_order.extend(['name_id', 'encrypted_id']) - - def __init__(self, name_id=None, encrypted_id=None, - id=None, in_response_to=None, - version=None, issue_instant=None, - destination=None, consent=None, issuer=None, signature=None, - extensions=None, status=None, - text=None, - extension_elements=None, extension_attributes=None): - """Constructor for NameIDMappingResponse - - :param name_id: The id - :param encrypted_id: associated descriptive data - :param id: ID attribute - :param in_respones_to: InResponseTo attribute - :param version: Version attribute - :param issue_instant: IssueInstant attribute - :param destination: Destination attribute - :param consent: Consent attribute - :param issuer: Issuer element - :param signature: Signature element - :param extensions: Extensions element - :param status: Status element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value - string pairs - """ - StatusResponse.__init__(self, id, in_response_to, - version, issue_instant, destination, consent, - issuer, signature, extensions, status, - text, extension_elements, extension_attributes) - - self.name_id = name_id - self.encrypted_id = encrypted_id + c_children = NameIDMappingResponseType.c_children.copy() + c_attributes = NameIDMappingResponseType.c_attributes.copy() + c_child_order = NameIDMappingResponseType.c_child_order[:] def name_id_mapping_response_from_string(xml_string): - """ Create NameIDMappingResponse instance from an XML string """ - return create_class_from_xml_string(NameIDMappingResponse, xml_string) + return saml2.create_class_from_xml_string(NameIDMappingResponse, xml_string) + +#.................. +# ['StatusCode', 'StatusCodeType'] +class StatusCodeType(SamlBase): + """The urn:oasis:names:tc:SAML:2.0:protocol:StatusCodeType element """ + + c_tag = 'StatusCodeType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['Value'] = ('value', 'anyURI', True) + c_child_order.extend(['status_code']) + + def __init__(self, + status_code=None, + value=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.status_code=status_code + self.value=value + +def status_code_type_from_string(xml_string): + return saml2.create_class_from_xml_string(StatusCodeType, xml_string) + +class StatusCode(StatusCodeType): + """The urn:oasis:names:tc:SAML:2.0:protocol:StatusCode element """ + + c_tag = 'StatusCode' + c_namespace = NAMESPACE + c_children = StatusCodeType.c_children.copy() + c_attributes = StatusCodeType.c_attributes.copy() + c_child_order = StatusCodeType.c_child_order[:] + +def status_code_from_string(xml_string): + return saml2.create_class_from_xml_string(StatusCode, xml_string) + +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +StatusType.c_children['{urn:oasis:names:tc:SAML:2.0:protocol}StatusCode'] = ('status_code', StatusCode) +Status.c_children['{urn:oasis:names:tc:SAML:2.0:protocol}StatusCode'] = ('status_code', StatusCode) +StatusCodeType.c_children['{urn:oasis:names:tc:SAML:2.0:protocol}StatusCode'] = ('status_code', StatusCode) +StatusCode.c_children['{urn:oasis:names:tc:SAML:2.0:protocol}StatusCode'] = ('status_code', StatusCode) +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +ELEMENT_FROM_STRING = { + RequestAbstractType.c_tag: request_abstract_type_from_string, + Extensions.c_tag: extensions_from_string, + ExtensionsType.c_tag: extensions_type_from_string, + StatusResponseType.c_tag: status_response_type_from_string, + Status.c_tag: status_from_string, + StatusType.c_tag: status_type_from_string, + StatusCode.c_tag: status_code_from_string, + StatusCodeType.c_tag: status_code_type_from_string, + StatusMessage.c_tag: status_message_from_string, + StatusDetail.c_tag: status_detail_from_string, + StatusDetailType.c_tag: status_detail_type_from_string, + AssertionIDRequest.c_tag: assertion_id_request_from_string, + AssertionIDRequestType.c_tag: assertion_id_request_type_from_string, + SubjectQuery.c_tag: subject_query_from_string, + SubjectQueryAbstractType.c_tag: subject_query_abstract_type_from_string, + AuthnQuery.c_tag: authn_query_from_string, + AuthnQueryType.c_tag: authn_query_type_from_string, + RequestedAuthnContext.c_tag: requested_authn_context_from_string, + RequestedAuthnContextType.c_tag: requested_authn_context_type_from_string, + AuthnContextComparisonType.c_tag: authn_context_comparison_type_from_string, + AttributeQuery.c_tag: attribute_query_from_string, + AttributeQueryType.c_tag: attribute_query_type_from_string, + AuthzDecisionQuery.c_tag: authz_decision_query_from_string, + AuthzDecisionQueryType.c_tag: authz_decision_query_type_from_string, + AuthnRequest.c_tag: authn_request_from_string, + AuthnRequestType.c_tag: authn_request_type_from_string, + NameIDPolicy.c_tag: name_id_policy_from_string, + NameIDPolicyType.c_tag: name_id_policy_type_from_string, + Scoping.c_tag: scoping_from_string, + ScopingType.c_tag: scoping_type_from_string, + RequesterID.c_tag: requester_id_from_string, + IDPList.c_tag: idp_list_from_string, + IDPListType.c_tag: idp_list_type_from_string, + IDPEntry.c_tag: idp_entry_from_string, + IDPEntryType.c_tag: idp_entry_type_from_string, + GetComplete.c_tag: get_complete_from_string, + Response.c_tag: response_from_string, + ResponseType.c_tag: response_type_from_string, + ArtifactResolve.c_tag: artifact_resolve_from_string, + ArtifactResolveType.c_tag: artifact_resolve_type_from_string, + Artifact.c_tag: artifact_from_string, + ArtifactResponse.c_tag: artifact_response_from_string, + ArtifactResponseType.c_tag: artifact_response_type_from_string, + ManageNameIDRequest.c_tag: manage_name_id_request_from_string, + ManageNameIDRequestType.c_tag: manage_name_id_request_type_from_string, + NewID.c_tag: new_id_from_string, + NewEncryptedID.c_tag: new_encrypted_id_from_string, + Terminate.c_tag: terminate_from_string, + TerminateType.c_tag: terminate_type_from_string, + ManageNameIDResponse.c_tag: manage_name_id_response_from_string, + LogoutRequest.c_tag: logout_request_from_string, + LogoutRequestType.c_tag: logout_request_type_from_string, + SessionIndex.c_tag: session_index_from_string, + LogoutResponse.c_tag: logout_response_from_string, + NameIDMappingRequest.c_tag: name_id_mapping_request_from_string, + NameIDMappingRequestType.c_tag: name_id_mapping_request_type_from_string, + NameIDMappingResponse.c_tag: name_id_mapping_response_from_string, + NameIDMappingResponseType.c_tag: name_id_mapping_response_type_from_string, +} + +ELEMENT_BY_TAG = { + 'RequestAbstractType': RequestAbstractType, + 'Extensions': Extensions, + 'ExtensionsType': ExtensionsType, + 'StatusResponseType': StatusResponseType, + 'Status': Status, + 'StatusType': StatusType, + 'StatusCode': StatusCode, + 'StatusCodeType': StatusCodeType, + 'StatusMessage': StatusMessage, + 'StatusDetail': StatusDetail, + 'StatusDetailType': StatusDetailType, + 'AssertionIDRequest': AssertionIDRequest, + 'AssertionIDRequestType': AssertionIDRequestType, + 'SubjectQuery': SubjectQuery, + 'SubjectQueryAbstractType': SubjectQueryAbstractType, + 'AuthnQuery': AuthnQuery, + 'AuthnQueryType': AuthnQueryType, + 'RequestedAuthnContext': RequestedAuthnContext, + 'RequestedAuthnContextType': RequestedAuthnContextType, + 'AuthnContextComparisonType': AuthnContextComparisonType, + 'AttributeQuery': AttributeQuery, + 'AttributeQueryType': AttributeQueryType, + 'AuthzDecisionQuery': AuthzDecisionQuery, + 'AuthzDecisionQueryType': AuthzDecisionQueryType, + 'AuthnRequest': AuthnRequest, + 'AuthnRequestType': AuthnRequestType, + 'NameIDPolicy': NameIDPolicy, + 'NameIDPolicyType': NameIDPolicyType, + 'Scoping': Scoping, + 'ScopingType': ScopingType, + 'RequesterID': RequesterID, + 'IDPList': IDPList, + 'IDPListType': IDPListType, + 'IDPEntry': IDPEntry, + 'IDPEntryType': IDPEntryType, + 'GetComplete': GetComplete, + 'Response': Response, + 'ResponseType': ResponseType, + 'ArtifactResolve': ArtifactResolve, + 'ArtifactResolveType': ArtifactResolveType, + 'Artifact': Artifact, + 'ArtifactResponse': ArtifactResponse, + 'ArtifactResponseType': ArtifactResponseType, + 'ManageNameIDRequest': ManageNameIDRequest, + 'ManageNameIDRequestType': ManageNameIDRequestType, + 'NewID': NewID, + 'NewEncryptedID': NewEncryptedID, + 'Terminate': Terminate, + 'TerminateType': TerminateType, + 'ManageNameIDResponse': ManageNameIDResponse, + 'LogoutRequest': LogoutRequest, + 'LogoutRequestType': LogoutRequestType, + 'SessionIndex': SessionIndex, + 'LogoutResponse': LogoutResponse, + 'NameIDMappingRequest': NameIDMappingRequest, + 'NameIDMappingRequestType': NameIDMappingRequestType, + 'NameIDMappingResponse': NameIDMappingResponse, + 'NameIDMappingResponseType': NameIDMappingResponseType, +} + +def factory(tag, **kwargs): + return ELEMENT_BY_TAG[tag](**kwargs) diff --git a/src/saml2/server.py b/src/saml2/server.py index 1b28e7b..0fbb8d3 100644 --- a/src/saml2/server.py +++ b/src/saml2/server.py @@ -24,13 +24,13 @@ import sys from saml2 import saml, samlp, VERSION, class_name -from saml2.utils import sid, decode_base64_and_inflate -from saml2.utils import response_factory -from saml2.utils import MissingValue, args2dict -from saml2.utils import success_status_factory -from saml2.utils import OtherError -from saml2.utils import VersionMismatch, UnknownPrincipal, UnsupportedBinding -from saml2.utils import status_from_exception_factory +from saml2.s_utils import sid, decode_base64_and_inflate +from saml2.s_utils import response_factory +from saml2.s_utils import MissingValue, factory +from saml2.s_utils import success_status_factory +from saml2.s_utils import OtherError +from saml2.s_utils import VersionMismatch, UnknownPrincipal, UnsupportedBinding +from saml2.s_utils import status_from_exception_factory from saml2.sigver import security_context, signed_instance_factory from saml2.sigver import pre_signature_part @@ -104,9 +104,12 @@ class Identifier(object): nameid_format = vo_conf["nameid_format"] except KeyError: nameid_format = saml.NAMEID_FORMAT_PERSISTENT - - return args2dict(subj_id, format=nameid_format, - sp_name_qualifier=sp_name_qualifier) + + return saml.NameID(format=nameid_format, + sp_name_qualifier=sp_name_qualifier, + text=subj_id) + # return args2dict(subj_id, format=nameid_format, + # sp_name_qualifier=sp_name_qualifier) def persistent_nameid(self, sp_name_qualifier, userid): """ Get or create a persistent identifier for this object to be used @@ -117,8 +120,18 @@ class Identifier(object): :return: A persistent random identifier. """ subj_id = self.persistent(sp_name_qualifier, userid) - return args2dict(subj_id, format=saml.NAMEID_FORMAT_PERSISTENT, - sp_name_qualifier=sp_name_qualifier) + return saml.NameID(format=saml.NAMEID_FORMAT_PERSISTENT, + sp_name_qualifier=sp_name_qualifier, + text=subj_id) + + # return args2dict(subj_id, format=saml.NAMEID_FORMAT_PERSISTENT, + # sp_name_qualifier=sp_name_qualifier) + + def temporary_nameid(self): + """ Returns a random one-time identifier """ + return saml.NameID(format=saml.NAMEID_FORMAT_TRANSIENT, + text=sid()) + #return args2dict(sid(), format=saml.NAMEID_FORMAT_TRANSIENT) def construct_nameid(self, local_policy, userid, sp_entity_id, identity=None, name_id_policy=None): @@ -143,9 +156,6 @@ class Identifier(object): elif nameid_format == saml.NAMEID_FORMAT_TRANSIENT: return self.temporary_nameid() - def temporary_nameid(self): - """ Returns a random one-time identifier """ - return args2dict(sid(), format=saml.NAMEID_FORMAT_TRANSIENT) class Server(object): @@ -181,9 +191,8 @@ class Server(object): def issuer(self): """ Return an Issuer precursor """ - return args2dict( self.conf["entityid"], - format=saml.NAMEID_FORMAT_ENTITY) - + return saml.Issuer(text=self.conf["entityid"], + format=saml.NAMEID_FORMAT_ENTITY) def parse_authn_request(self, enc_request): """Parse a Authentication Request @@ -298,6 +307,8 @@ class Server(object): :return: A Response instance """ + to_sign = [] + if not status: status = success_status_factory() @@ -323,19 +334,21 @@ class Server(object): policy, issuer=_issuer) if sign: - assertion["signature"] = pre_signature_part(assertion["id"], + assertion.signature = pre_signature_part(assertion.id, self.sec.my_cert, 1) + # Just the assertion or the response and the assertion ? + to_sign = [(class_name(assertion), assertion.id)] # Store which assertion that has been sent to which SP about which # subject. - self.cache.set(assertion["subject"]["name_id"]["text"], + self.cache.set(assertion.subject.name_id.text, sp_entity_id, assertion, - assertion["conditions"]["not_on_or_after"]) + assertion.conditions.not_on_or_after) - response.update({"assertion":assertion}) + response.assertion = assertion - return signed_instance_factory(samlp.Response, response, self.sec) + return signed_instance_factory(response, self.sec, to_sign) # ------------------------------------------------------------------------ diff --git a/src/saml2/sigver.py b/src/saml2/sigver.py index e366a2c..9165d2b 100644 --- a/src/saml2/sigver.py +++ b/src/saml2/sigver.py @@ -19,7 +19,7 @@ Based on the use of xmlsec1 binaries and not the python xmlsec module. """ -from saml2 import samlp, class_name, saml, make_instance +from saml2 import samlp, class_name, saml, ExtensionElement from saml2 import create_class_from_xml_string import xmldsig as ds from tempfile import NamedTemporaryFile @@ -27,12 +27,11 @@ from subprocess import Popen, PIPE import base64 import random import os -import copy def get_xmlsec_binary(): for path in os.environ["PATH"].split(":"): fil = os.path.join(path, "xmlsec1") - if os.access(fil,os.X_OK): + if os.access(fil, os.X_OK): return fil raise Exception("Can't find xmlsec1") @@ -86,12 +85,12 @@ def _make_vals(val, klass, seccont, klass_inst=None, prop=None, part=False, #print "make_vals(%s, %s)" % (val, klass) if isinstance(val, dict): - cinst = _instance(klass, val, seccont,base64encode=base64encode, + cinst = _instance(klass, val, seccont, base64encode=base64encode, elements_to_sign=elements_to_sign) else: try: cinst = klass().set_text(val) - except ValueError, excp: + except ValueError: if not part: cis = [_make_vals(sval, klass, seccont, klass_inst, prop, True, base64encode, elements_to_sign) for sval in val] @@ -150,16 +149,12 @@ def _instance(klass, ava, seccont, base64encode=False, elements_to_sign=None): return instance -def signed_instance_factory(klass, ava, seccont, base64encode=False): - elements_to_sign = [] - instance = _instance(klass, ava, seccont, base64encode=False, - elements_to_sign=elements_to_sign) - +def signed_instance_factory(instance, seccont, elements_to_sign=None): if elements_to_sign: signed_xml = "%s" % instance for (node_name, nodeid) in elements_to_sign: signed_xml = seccont.sign_statement_using_xmlsec(signed_xml, - class_name=node_name, nodeid=nodeid) + klass_namn=node_name, nodeid=nodeid) #print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" #print "%s" % signed_xml @@ -274,7 +269,7 @@ def verify_signature(enctext, xmlsec_binary, cert_file=None, cert_type="pem", com_list.append("--store-signatures") if node_id: - com_list.extend(["--node-id",node_id]) + com_list.extend(["--node-id", node_id]) com_list.append(fil) @@ -351,6 +346,7 @@ class SecurityContext(object): # Your private key self.key_file = key_file + self.key_type = key_type # Your certificate self.cert_file = cert_file @@ -379,7 +375,7 @@ class SecurityContext(object): ntf = NamedTemporaryFile() com_list = [self.xmlsec, "--decrypt", - "--privkey-pem", key_file, + "--privkey-pem", self.key_file, "--output", ntf.name, "--id-attr:%s" % ID_ATTR, ENC_NODE_NAME, fil] @@ -503,11 +499,11 @@ class SecurityContext(object): return response - #---------------------------------------------------------------------------- + #-------------------------------------------------------------------------- # SIGNATURE PART - #---------------------------------------------------------------------------- + #-------------------------------------------------------------------------- - def sign_statement_using_xmlsec(self, statement, class_name, key=None, + def sign_statement_using_xmlsec(self, statement, klass_namn, key=None, key_file=None, nodeid=None): """Sign a SAML statement using xmlsec. @@ -530,11 +526,11 @@ class SecurityContext(object): com_list = [self.xmlsec, "--sign", "--output", ntf.name, "--privkey-pem", key_file, - "--id-attr:%s" % ID_ATTR, class_name, + "--id-attr:%s" % ID_ATTR, klass_namn, #"--store-signatures" ] if nodeid: - com_list.extend(["--node-id",nodeid]) + com_list.extend(["--node-id", nodeid]) com_list.append(fil) @@ -543,9 +539,9 @@ class SecurityContext(object): # this doesn't work if --store-signatures are used if out == "": #print " ".join(com_list) - #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" #print out - #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" ntf.seek(0) return ntf.read() else: @@ -568,39 +564,65 @@ class SecurityContext(object): # =========================================================================== -PRE_SIGNATURE = { - "signed_info": { - "signature_method": { - "algorithm": ds.SIG_RSA_SHA1 - }, - "canonicalization_method": { - "algorithm": ds.ALG_EXC_C14N - }, - "reference": { - # must be replace by a uriref based on the assertion ID - "uri": None, - "transforms": { - "transform": [{ - "algorithm": ds.TRANSFORM_ENVELOPED, - }, - { - "algorithm": ds.ALG_EXC_C14N, - "inclusive_namespaces": { - "prefix_list": "ds saml2 saml2p xenc", - } - } - ] - }, - "digest_method":{ - "algorithm": ds.DIGEST_SHA1, - }, - "digest_value": "", - } - }, - "signature_value": None, -} +# PRE_SIGNATURE = { +# "signed_info": { +# "signature_method": { +# "algorithm": ds.SIG_RSA_SHA1 +# }, +# "canonicalization_method": { +# "algorithm": ds.ALG_EXC_C14N +# }, +# "reference": { +# # must be replace by a uriref based on the assertion ID +# "uri": None, +# "transforms": { +# "transform": [{ +# "algorithm": ds.TRANSFORM_ENVELOPED, +# }, +# { +# "algorithm": ds.ALG_EXC_C14N, +# "inclusive_namespaces": { +# "prefix_list": "ds saml2 saml2p xenc", +# } +# } +# ] +# }, +# "digest_method":{ +# "algorithm": ds.DIGEST_SHA1, +# }, +# "digest_value": "", +# } +# }, +# "signature_value": None, +# } +# +# def pre_signature_part(ident, public_key=None, id=None): +# """ +# If an assertion is to be signed the signature part has to be preset +# with which algorithms to be used, this function returns such a +# preset part. +# +# :param ident: The identifier of the assertion, so you know which assertion +# was signed +# :param public_key: The base64 part of a PEM file +# :return: A preset signature part +# """ +# +# presig = copy.deepcopy(PRE_SIGNATURE) +# presig["signed_info"]["reference"]["uri"] = "#%s" % ident +# if id: +# presig["id"] = "Signature%d" % id +# if public_key: +# presig["key_info"] = { +# "x509_data": { +# "x509_certificate": public_key, +# } +# } +# +# return presig -def pre_signature_part(ident, public_key=None, id=None): + +def pre_signature_part(ident, public_key=None, identifier=None): """ If an assertion is to be signed the signature part has to be preset with which algorithms to be used, this function returns such a @@ -611,16 +633,34 @@ def pre_signature_part(ident, public_key=None, id=None): :param public_key: The base64 part of a PEM file :return: A preset signature part """ + + signature_method = ds.SignatureMethod(algorithm = ds.SIG_RSA_SHA1) + canonicalization_method = ds.CanonicalizationMethod( + algorithm = ds.ALG_EXC_C14N) + trans0 = ds.Transform(algorithm = ds.TRANSFORM_ENVELOPED) + trans1 = ds.Transform(algorithm = ds.ALG_EXC_C14N) + transforms = ds.Transforms(transform = [trans0, trans1]) + digest_method = ds.DigestMethod(algorithm = ds.DIGEST_SHA1) - presig = copy.deepcopy(PRE_SIGNATURE) - presig["signed_info"]["reference"]["uri"] = "#%s" % ident - if id: - presig["id"] = "Signature%d" % id + reference = ds.Reference(uri = "#%s" % ident, + digest_value = ds.DigestValue(), + transforms = transforms, + digest_method = digest_method) + + signed_info = ds.SignedInfo(signature_method = signature_method, + canonicalization_method = canonicalization_method, + reference = reference) + + signature = ds.Signature(signed_info=signed_info, + signature_value=ds.SignatureValue()) + + if identifier: + signature.id = "Signature%d" % identifier + if public_key: - presig["key_info"] = { - "x509_data": { - "x509_certificate": public_key, - } - } - - return presig + x509_data = ds.X509Data(x509_certificate=[ds.X509Certificate(text=public_key)]) + key_info = ds.KeyInfo(x509_data=x509_data) + signature.key_info = key_info + + return signature + \ No newline at end of file diff --git a/src/saml2/soap.py b/src/saml2/soap.py index 2d4324c..9c99750 100644 --- a/src/saml2/soap.py +++ b/src/saml2/soap.py @@ -62,7 +62,7 @@ def parse_soap_enveloped_saml_thingy(text, expected_tag): else: return "" -def make_soap_enveloped_saml_thingy(thingy): +def make_soap_enveloped_saml_thingy(thingy, headers=None): """ Returns a soap envelope containing a SAML request as a text string. @@ -72,6 +72,13 @@ def make_soap_enveloped_saml_thingy(thingy): envelope = ElementTree.Element('') envelope.tag = '{%s}Envelope' % NAMESPACE + if headers: + header = ElementTree.Element('') + header.tag = '{%s}Header' % NAMESPACE + envelope.append(header) + for head in headers: + head.become_child_element(header) + body = ElementTree.Element('') body.tag = '{%s}Body' % NAMESPACE envelope.append(body) diff --git a/src/saml2/utils.py b/src/saml2/utils.py index 2f0c3f6..cc02c52 100644 --- a/src/saml2/utils.py +++ b/src/saml2/utils.py @@ -189,6 +189,17 @@ def response_factory(signature=False, encrypt=False, **kwargs): pass return args2dict(**kwargs) +def response_factory_x(signature=False, encrypt=False, **kwargs): + response = samlp.Response(id=sid(), version=VERSION, issue_instant=instant()) + + if signature: + kwargs["signature"] = sigver.pre_signature_part(kwargs["id"]) + + if encrypt: + pass + + return response + def _attrval(val): if isinstance(val, list) or isinstance(val, set): attrval = [args2dict(v) for v in val] diff --git a/src/xmldsig/__init__.py b/src/xmldsig/__init__.py index 5e7bd49..56799f8 100644 --- a/src/xmldsig/__init__.py +++ b/src/xmldsig/__init__.py @@ -1,44 +1,15 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- +#!/usr/bin/env python + # -# Copyright (C) 2007 SIOS Technology, Inc. -# Copyright (C) 2009 Umeå University +# Generated Thu Jul 15 20:56:45 2010 by parse_xsd.py version 0.2. # -# 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. -"""Contains classes representing xmldsig elements. - - Module objective: provide data classes for xmldsig constructs. These - classes hide the XML-ness of Saml and provide a set of native Python - classes to interact with. - - Classes in this module inherits saml.SamlBase now. - -""" - -try: - from xml.etree import cElementTree as ElementTree -except ImportError: - try: - import cElementTree as ElementTree - except ImportError: - from elementtree import ElementTree import saml2 -#import xmlenc -from saml2 import create_class_from_xml_string +from saml2 import SamlBase + NAMESPACE = 'http://www.w3.org/2000/09/xmldsig#' -TEMPLATE = '{http://www.w3.org/2000/09/xmldsig#}%s' + ENCODING_BASE64 = 'http://www.w3.org/2000/09/xmldsig#base64' DIGEST_SHA1 = 'http://www.w3.org/2000/09/xmldsig#sha1' @@ -55,1057 +26,1416 @@ TRANSFORM_XPATH = 'http://www.w3.org/TR/1999/REC-xpath-19991116' TRANSFORM_ENVELOPED = 'http://www.w3.org/2000/09/xmldsig#enveloped-signature' -class DsBase(saml2.SamlBase): - """The ds:DsBase element""" +class CryptoBinary(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:CryptoBinary element """ - c_children = {} - c_attributes = {} - -class Object(DsBase): - """The ds:Object element""" - - c_tag = 'Object' + c_tag = 'CryptoBinary' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Id'] = 'identifier' - c_attributes['MimeType'] = 'mime_type' - c_attributes['Encoding'] = 'encoding' + c_value_type = {'base': 'base64Binary'} + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - def __init__(self, identifier=None, mime_type=None, encoding=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for Object +def crypto_binary_from_string(xml_string): + return saml2.create_class_from_xml_string(CryptoBinary, xml_string) - :param identifier: Id attribute - :param mime_type: MimeType attribute - :param encoding: Encoding attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +class SignatureValueType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:SignatureValueType element """ - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.identifier = identifier - self.mime_type = mime_type - self.encoding = encoding - -def object_from_string(xml_string): - """ Create Object instance from an XML string """ - return create_class_from_xml_string(Object, xml_string) - -class MgmtData(DsBase): - """The ds:MgmtData element""" - - c_tag = 'MgmtData' + c_tag = 'SignatureValueType' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['Id'] = ('id', 'ID', False) -def mgmt_data_from_string(xml_string): - """ Create MgmtData instance from an XML string """ - return create_class_from_xml_string(MgmtData, xml_string) + def __init__(self, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.id=id +def signature_value_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SignatureValueType, xml_string) -class SPKISexp(DsBase): - """The ds:SPKISexp element""" +class CanonicalizationMethodType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:CanonicalizationMethodType element """ - c_tag = 'SPKISexp' + c_tag = 'CanonicalizationMethodType' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def spki_sexp_from_string(xml_string): - """ Create SPKISexp instance from an XML string """ - return create_class_from_xml_string(SPKISexp, xml_string) - - -class SPKIData(DsBase): - """The ds:SPKIData element""" - - c_tag = 'SPKIData' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_children['{%s}SPKISexp' % NAMESPACE] = ('spki_sexp', [SPKISexp]) - - def __init__(self, spki_sexp=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for SPKIData - - :param spki_sexp: SPKISexp elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.spki_sexp = spki_sexp or [] - -def spki_data_from_string(xml_string): - """ Create SPKIData instance from an XML string """ - return create_class_from_xml_string(SPKIData, xml_string) - - -class PGPKeyID(DsBase): - """The ds:PGPKeyID element""" - - c_tag = 'PGPKeyID' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def pgp_key_id_from_string(xml_string): - """ Create PGPKeyID instance from an XML string """ - return create_class_from_xml_string(PGPKeyID, xml_string) - - -class PGPKeyPacket(DsBase): - """The ds:PGPKeyPacket element""" - - c_tag = 'PGPKeyPacket' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def pgp_key_packet_from_string(xml_string): - """ Create PGPKeyPacket instance from an XML string """ - return create_class_from_xml_string(PGPKeyPacket, xml_string) - - -class PGPData(DsBase): - """The ds:PGPData element""" - - c_tag = 'PGPData' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_children['{%s}PGPKeyID' % NAMESPACE] = ('pgp_key_id', PGPKeyID) - c_children['{%s}PGPKeyPacket' % NAMESPACE] = ( - 'pgp_key_packet', PGPKeyPacket) - c_child_order = ['pgp_key_id', 'pgp_key_packet'] - - def __init__(self, pgp_key_id=None, pgp_key_packet=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for PGPKeyINfo - - :param pgp_key_id: PGPKeyID element - :param pgp_key_packet: PGPKeyPacket element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.pgp_key_id = pgp_key_id - self.pgp_key_packet = pgp_key_packet - -def pgp_data_from_string(xml_string): - """ Create PGPData instance from an XML string """ - return create_class_from_xml_string(PGPData, xml_string) - - -class X509IssuerName(DsBase): - """The ds:X509IssuerName element""" - - c_tag = 'X509IssuerName' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def x509_issuer_name_from_string(xml_string): - """ Create X509IssuerName instance from an XML string """ - return create_class_from_xml_string(X509IssuerName, xml_string) - - -class X509IssuerNumber(DsBase): - """The ds:X509IssuerNumber element""" - - c_tag = 'X509IssuerNumber' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def x509_issuer_number_from_string(xml_string): - """ Create X509IssuerNumber instance from an XML string """ - return create_class_from_xml_string(X509IssuerNumber, xml_string) - - -class X509IssuerSerial(DsBase): - """The ds:X509IssuerSerial element""" - - c_tag = 'X509IssuerSerial' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_children['{%s}X509IssuerName' % NAMESPACE] = ( - 'x509_issuer_name', X509IssuerName) - c_children['{%s}X509IssuerNumber' % NAMESPACE] = ( - 'x509_issuer_number', X509IssuerNumber) - c_child_order = ['x509_issuer_name', 'x509_issuer_number'] - - def __init__(self, x509_issuer_name=None, x509_issuer_number=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for X509IssuerSerial - - :param x509_issuer_name: X509IssuerName - :param x509_issuer_number: X509IssuerNumber - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.x509_issuer_name = x509_issuer_name - self.x509_issuer_number = x509_issuer_number - - -def x509_issuer_serial_from_string(xml_string): - """ Create X509IssuerSerial instance from an XML string """ - return create_class_from_xml_string(X509IssuerSerial, xml_string) - - -class X509SKI(DsBase): - """The ds:X509SKI element""" - - c_tag = 'X509SKI' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def x509_ski_from_string(xml_string): - """ Create X509SKI instance from an XML string """ - return create_class_from_xml_string(X509SKI, xml_string) - - -class X509SubjectName(DsBase): - """The ds:X509SubjectName element""" - - c_tag = 'X509SubjectName' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def x509_subject_name_from_string(xml_string): - """ Create X509SubjectName instance from an XML string """ - return create_class_from_xml_string(X509SubjectName, xml_string) - - -class X509Certificate(DsBase): - """The ds:X509Certificate element""" - - c_tag = 'X509Certificate' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def x509_certificate_from_string(xml_string): - """ Create X509Certificate instance from an XML string """ - return create_class_from_xml_string(X509Certificate, xml_string) - - -class X509CRL(DsBase): - """The ds:X509CRL element""" - - c_tag = 'X509CRL' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def x509_crl_from_string(xml_string): - """ Create X509CRL instance from an XML string """ - return create_class_from_xml_string(X509CRL, xml_string) - - -class X509Data(DsBase): - """The ds:X509Data element""" - - c_tag = 'X509Data' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_children['{%s}X509IssuerSerial' % NAMESPACE] = ( - 'x509_issuer_serial', [X509IssuerSerial]) - c_children['{%s}X509SKI' % NAMESPACE] = ('x509_ski', [X509SKI]) - c_children['{%s}X509SubjectName' % NAMESPACE] = ( - 'x509_subject_name', [X509SubjectName]) - c_children['{%s}X509Certificate' % NAMESPACE] = ( - 'x509_certificate', [X509Certificate]) - c_children['{%s}X509CRL' % NAMESPACE] = ('x509_crl', [X509CRL]) - c_child_order = ['x509_issuer_serial', 'x509_ski', 'x509_subject_name', - 'x509_certificate', 'x509_crl'] - - def __init__(self, x509_issuer_serial=None, x509_ski=None, - x509_subject_name=None, x509_certificate=None, x509_crl=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for X509Data - - :param x509_issuer_serial: X509IssuerSerial element - :param x509_ski: X509SKI element - :param x509_subject_name: X509SubjectName element - :param x509_certificate: X509Certificate element - :param x509_crl: X509CRL element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.x509_issuer_serial = x509_issuer_serial or [] - self.x509_ski = x509_ski or [] - self.x509_subject_name = x509_subject_name or [] - self.x509_certificate = x509_certificate or [] - self.x509_crl = x509_crl or [] - - -def x509_data_from_string(xml_string): - """ Create X509Data instance from an XML string """ - return create_class_from_xml_string(X509Data, xml_string) - - -class XPath(DsBase): - """The ds:XPath element""" + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['Algorithm'] = ('algorithm', 'anyURI', True) + + def __init__(self, + algorithm=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.algorithm=algorithm + +def canonicalization_method_type_from_string(xml_string): + return saml2.create_class_from_xml_string(CanonicalizationMethodType, xml_string) + +class XPath(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:XPath element """ c_tag = 'XPath' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def xpath_from_string(xml_string): - """ Create XPath instance from an XML string """ - return create_class_from_xml_string(XPath, xml_string) +def x_path_from_string(xml_string): + return saml2.create_class_from_xml_string(XPath, xml_string) +class TransformType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:TransformType element """ -class Transform(DsBase): - """The ds:Transform element""" - - c_tag = 'Transform' + c_tag = 'TransformType' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Algorithm'] = 'algorithm' - c_children['{%s}XPath' % NAMESPACE] = ('xpath', [XPath]) + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}XPath'] = ('x_path', [XPath]) + c_attributes['Algorithm'] = ('algorithm', 'anyURI', True) + c_child_order.extend(['x_path']) - def __init__(self, xpath=None, algorithm=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for Transform + def __init__(self, + x_path=None, + algorithm=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.x_path=x_path or [] + self.algorithm=algorithm - :param xpath: XPath elements - :param algorithm: Algorithm attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +def transform_type_from_string(xml_string): + return saml2.create_class_from_xml_string(TransformType, xml_string) - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.xpath = xpath or [] - self.algorithm = algorithm +class DigestMethodType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:DigestMethodType element """ -def transform_from_string(xml_string): - """ Create Transform instance from an XML string """ - return create_class_from_xml_string(Transform, xml_string) - - -class Transforms(DsBase): - """The ds:Transforms element""" - - c_tag = 'Transforms' + c_tag = 'DigestMethodType' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_children['{%s}Transform' % NAMESPACE] = ('transform', [Transform]) + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['Algorithm'] = ('algorithm', 'anyURI', True) - def __init__(self, transform=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for Transforms + def __init__(self, + algorithm=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.algorithm=algorithm - :param transform: Transform elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +def digest_method_type_from_string(xml_string): + return saml2.create_class_from_xml_string(DigestMethodType, xml_string) - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.transform = transform or [] +class DigestValueType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:DigestValueType element """ -def transforms_from_string(xml_string): - """ Create Transforms instance from an XML string """ - return create_class_from_xml_string(Transforms, xml_string) - - -class RetrievalMethod(DsBase): - """The ds:RetrievalMethod element""" - - c_tag = 'RetrievalMethod' + c_tag = 'DigestValueType' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['URI'] = 'uri' - c_attributes['Type'] = 'type' - c_children['{%s}Transforms' % NAMESPACE] = ('transforms', [Transforms]) + c_value_type = {'base': 'base64Binary'} + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - def __init__(self, transforms=None, uri=None, type=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for RetrievalMethod +def digest_value_type_from_string(xml_string): + return saml2.create_class_from_xml_string(DigestValueType, xml_string) - :param transforms: Transforms elements - :param uri: URI attribute - :param typ: Type attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.uri = uri - self.type = type - self.transforms = transforms or [] - -def retrieval_method_from_string(xml_string): - """ Create RetrievalMethod instance from an XML string """ - return create_class_from_xml_string(RetrievalMethod, xml_string) - - -class Modulus(DsBase): - """The ds:Modulus element""" - - c_tag = 'Modulus' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def modulus_from_string(xml_string): - """ Create Modulus instance from an XML string """ - return create_class_from_xml_string(Modulus, xml_string) - - -class Exponent(DsBase): - """The ds:Exponent element""" - - c_tag = 'Exponent' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def exponent_from_string(xml_string): - """ Create Exponent instance from an XML string """ - return create_class_from_xml_string(Exponent, xml_string) - - -class RSAKeyValue(DsBase): - """The ds:RSAKeyValue element""" - - c_tag = 'RSAKeyValue' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_children['{%s}Modulus' % NAMESPACE] = ('modulus', Modulus) - c_children['{%s}Exponent' % NAMESPACE] = ('exponent', Exponent) - c_child_order = ['modulus', 'exponent'] - - def __init__(self, modulus=None, exponent=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for RSAKeyValue - - :param modulus: Modulus element - :param exponent: Exponent element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.modulus = modulus - self.exponent = exponent - -def rsa_key_value_from_string(xml_string): - """ Create RSAKeyValue instance from an XML string """ - return create_class_from_xml_string(RSAKeyValue, xml_string) - - -class DsP(DsBase): - """The ds:P element""" - - c_tag = 'P' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def p_from_string(xml_string): - """ Create DsP instance from an XML string """ - return create_class_from_xml_string(DsP, xml_string) - - -class DsQ(DsBase): - """The ds:Q element""" - - c_tag = 'Q' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def q_from_string(xml_string): - """ Create DsQ instance from an XML string """ - return create_class_from_xml_string(DsQ, xml_string) - - -class DsG(DsBase): - """The ds:G element""" - - c_tag = 'G' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def g_from_string(xml_string): - """ Create DsG instance from an XML string """ - return create_class_from_xml_string(DsG, xml_string) - - -class DsY(DsBase): - """The ds:Y element""" - - c_tag = 'Y' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def y_from_string(xml_string): - """ Create DsY instance from an XML string """ - return create_class_from_xml_string(DsY, xml_string) - - -class DsJ(DsBase): - """The ds:J element""" - - c_tag = 'J' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def j_from_string(xml_string): - """ Create DsJ instance from an XML string """ - return create_class_from_xml_string(DsJ, xml_string) - - -class Seed(DsBase): - """The ds:Seed element""" - - c_tag = 'Seed' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def seed_from_string(xml_string): - """ Create Seed instance from an XML string """ - return create_class_from_xml_string(Seed, xml_string) - - -class PgenCounter(DsBase): - """The ds:PgenCounter element""" - - c_tag = 'PgenCounter' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - -def pgen_counter_from_string(xml_string): - """ Create PgenCounter instance from an XML string """ - return create_class_from_xml_string(PgenCounter, xml_string) - - -class DSAKeyValue(DsBase): - """The ds:DSAKeyValue element""" - - c_tag = 'DSAKeyValue' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_children['{%s}P' % NAMESPACE] = ('p', DsP) - c_children['{%s}Q' % NAMESPACE] = ('q', DsQ) - c_children['{%s}G' % NAMESPACE] = ('g', DsG) - c_children['{%s}Y' % NAMESPACE] = ('y', DsY) - c_children['{%s}J' % NAMESPACE] = ('j', DsJ) - c_children['{%s}Seed' % NAMESPACE] = ('seed', Seed) - c_children['{%s}PgenCounter' % NAMESPACE] = ('pgen_counter', PgenCounter) - - c_child_order = ['p', 'q', 'g', 'y', 'j', 'seed', 'pgen_counter'] - - def __init__(self, p=None, q=None, g=None, y=None, j=None, seed=None, - pgen_counter=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for DSAKeyValue - - :param p: P element - :param q: Q element - :param g: G element - :param y: Y element - :param j: J element - :param seed: Seed element - :param pgen_counter: PgenCounter element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.p = p - self.q = q - self.g = g - self.y = y - self.j = j - self.seed = Seed - self.pgen_counter = pgen_counter - -def dsa_key_value_from_string(xml_string): - """ Create DSAKeyValue instance from an XML string """ - return create_class_from_xml_string(DSAKeyValue, xml_string) - - -class KeyValue(DsBase): - """The ds:KeyValue element""" - - c_tag = 'KeyValue' - c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_children['{%s}RSAKeyValue' % NAMESPACE] = ('rsa_key_value', - RSAKeyValue) - c_children['{%s}DSAKeyValue' % NAMESPACE] = ('dsa_key_value', - DSAKeyValue) - - c_child_order = ['rsa_key_value', 'dsa_key_value'] - - def __init__(self, rsa_key_value=None, dsa_key_value=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for DSAKeyValue - - :param rsa_key_value: RSAKeyValue element - :param dsa_key_value: DSAKeyValue element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.rsa_key_value = rsa_key_value - self.dsa_key_value = dsa_key_value - -def key_value_from_string(xml_string): - """ Create KeyValue instance from an XML string """ - return create_class_from_xml_string(KeyValue, xml_string) - - -class KeyName(DsBase): - """The ds:KeyName element""" +class KeyName(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:KeyName element """ c_tag = 'KeyName' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] def key_name_from_string(xml_string): - """ Create KeyName instance from an XML string """ - return create_class_from_xml_string(KeyName, xml_string) + return saml2.create_class_from_xml_string(KeyName, xml_string) +class MgmtData(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:MgmtData element """ -class KeyInfo(DsBase): - """The ds:KeyInfo element""" - - c_tag = 'KeyInfo' + c_tag = 'MgmtData' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Id'] = "identifier" - c_children['{%s}KeyName' % NAMESPACE] = ('key_name', [KeyName]) - c_children['{%s}KeyValue' % NAMESPACE] = ('key_value', [KeyValue]) - c_children['{%s}RetrievalMethod' % NAMESPACE] = ( - 'retrieval_method', [RetrievalMethod]) - c_children['{%s}X509Data' % NAMESPACE] = ('x509_data', [X509Data]) - c_children['{%s}PGPData' % NAMESPACE] = ('pgp_data', [PGPData]) - c_children['{%s}SPKIData' % NAMESPACE] = ('spki_data', [SPKIData]) - c_children['{%s}MgmtData' % NAMESPACE] = ('mgmt_data', [MgmtData]) -# c_children['{%s}EncryptedKey' % xmlenc.NAMESPACE] = ( -# 'encrypted_key', [xmlenc.EncryptedKey]) + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - c_child_order = ['key_name', 'key_value', 'retrieval_method', 'x509_data', - 'pgp_data', 'spki_data', 'mgmt_data', - 'encrypted_key'] +def mgmt_data_from_string(xml_string): + return saml2.create_class_from_xml_string(MgmtData, xml_string) - def __init__(self, key_name=None, key_value=None, retrieval_method=None, - x509_data=None, pgp_data=None, spki_data=None, mgmt_data=None, - encrypted_key=None, identifier=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for DSAKeyValue +class X509IssuerName(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:X509IssuerName element """ - :param key_name: KeyName elements - :param key_value: KeyValue elements - :param retrieval_method: RetrievalMethod elements - :param x509_data: X509Data elements - :param pgp_data: PGPData elements - :param spki_data: SPKIData elements - :param mgmt_data: MgmtData elements - :param identifier: Id attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.key_name = key_name or [] - self.key_value = key_value or [] - self.retrieval_method = retrieval_method or [] - self.x509_data = x509_data or [] - self.pgp_data = pgp_data or [] - self.spki_data = spki_data or [] - self.mgmt_data = mgmt_data or [] - self.encrypted_key = encrypted_key or [] - self.identifier = identifier - -def key_info_from_string(xml_string): - """ Create KeyInfo instance from an XML string """ - return create_class_from_xml_string(KeyInfo, xml_string) - - -class DigestValue(DsBase): - """The ds:DigestValue element""" - - c_tag = 'DigestValue' + c_tag = 'X509IssuerName' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def digest_value_from_string(xml_string): - """ Create DigestValue instance from an XML string """ - return create_class_from_xml_string(DigestValue, xml_string) +def x509_issuer_name_from_string(xml_string): + return saml2.create_class_from_xml_string(X509IssuerName, xml_string) +class X509SerialNumber(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:X509SerialNumber element """ -class DigestMethod(DsBase): - """The ds:DigestMethod element""" - - c_tag = 'DigestMethod' + c_tag = 'X509SerialNumber' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Algorithm'] = "algorithm" + c_value_type = 'integer' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - def __init__(self, algorithm=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for DigestMethod +def x509_serial_number_from_string(xml_string): + return saml2.create_class_from_xml_string(X509SerialNumber, xml_string) - :param algorithm: Algorithm attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +class X509IssuerSerialType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:X509IssuerSerialType element """ - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.algorithm = algorithm - -def digest_method_from_string(xml_string): - """ Create DigestMethod instance from an XML string """ - return create_class_from_xml_string(DigestMethod, xml_string) - - -class Reference(DsBase): - """The ds:Reference element""" - - c_tag = 'Reference' + c_tag = 'X509IssuerSerialType' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Id'] = "identifier" - c_attributes['URI'] = "uri" - c_attributes['Type'] = "type" - c_children['{%s}Transforms' % NAMESPACE] = ('transforms', [Transforms]) - c_children['{%s}DigestMethod' % NAMESPACE] = ( - 'digest_method', [DigestMethod]) - c_children['{%s}DigestValue' % NAMESPACE] = ('digest_value', - [DigestValue]) - c_child_order = ['transforms', 'digest_method', 'digest_value'] + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}X509IssuerName'] = ('x509_issuer_name', X509IssuerName) + c_children['{http://www.w3.org/2000/09/xmldsig#}X509SerialNumber'] = ('x509_serial_number', X509SerialNumber) + c_child_order.extend(['x509_issuer_name', 'x509_serial_number']) - def __init__(self, identifier=None, uri=None, typ=None, transforms=None, - digest_method=None, digest_value=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for Reference + def __init__(self, + x509_issuer_name=None, + x509_serial_number=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.x509_issuer_name=x509_issuer_name + self.x509_serial_number=x509_serial_number - Args: - :param identifier: Id attribute - :param uri: URI attribute - :param type: Type attribute - :param transforms: Transforms elements - :param digest_method: DigestMethod elements - :param digest_value: DigestValue elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +def x509_issuer_serial_type_from_string(xml_string): + return saml2.create_class_from_xml_string(X509IssuerSerialType, xml_string) - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.identifier = identifier - self.uri = uri - self.type = typ - self.transforms = transforms or [] - self.digest_method = digest_method or [] - self.digest_value = digest_value or [] +class PGPKeyID(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:PGPKeyID element """ -def reference_from_string(xml_string): - """ Create Reference instance from an XML string """ - return create_class_from_xml_string(Reference, xml_string) - - -class HMACOutputLength(DsBase): - """The ds:HMACOutputLength element""" - - c_tag = 'HMACOutputLength' + c_tag = 'PGPKeyID' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() + c_value_type = 'base64Binary' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def hmac_output_length_from_string(xml_string): - """ Create HMACOutputLength instance from an XML string """ - return create_class_from_xml_string(HMACOutputLength, xml_string) +def pgp_key_id_from_string(xml_string): + return saml2.create_class_from_xml_string(PGPKeyID, xml_string) +class PGPKeyPacket(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:PGPKeyPacket element """ -class SignatureMethod(DsBase): - """The ds:SignatureMethod element""" - - c_tag = 'SignatureMethod' + c_tag = 'PGPKeyPacket' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Algorithm'] = "algorithm" - c_children['{%s}HMACOutputLength' % NAMESPACE] = ( - 'hmac_output_length', HMACOutputLength) + c_value_type = 'base64Binary' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - def __init__(self, algorithm=None, hmac_output_length=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for SignatureMethod +def pgp_key_packet_from_string(xml_string): + return saml2.create_class_from_xml_string(PGPKeyPacket, xml_string) - :param algorighm: Algorithm attribute - :param hmac_output_length: HMACOutputLength element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +class PGPDataType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:PGPDataType element """ - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.algorithm = algorithm - self.hmac_output_length = hmac_output_length - -def signature_method_from_string(xml_string): - """ Create SignatureMethod instance from an XML string """ - return create_class_from_xml_string(SignatureMethod, xml_string) - - -class CanonicalizationMethod(DsBase): - """The ds:CanonicalizationMethod element""" - - c_tag = 'CanonicalizationMethod' + c_tag = 'PGPDataType' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Algorithm'] = "algorithm" + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}PGPKeyID'] = ('pgp_key_id', PGPKeyID) + c_children['{http://www.w3.org/2000/09/xmldsig#}PGPKeyPacket'] = ('pgp_key_packet', PGPKeyPacket) + c_child_order.extend(['pgp_key_id', 'pgp_key_packet']) - def __init__(self, algorithm=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for CanonicalizationMethod + def __init__(self, + pgp_key_id=None, + pgp_key_packet=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.pgp_key_id=pgp_key_id + self.pgp_key_packet=pgp_key_packet - :param algorighm: Algorithm attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +def pgp_data_type_from_string(xml_string): + return saml2.create_class_from_xml_string(PGPDataType, xml_string) - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.algorithm = algorithm +class SPKISexp(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:SPKISexp element """ -def canonicalization_method_from_string(xml_string): - """ Create CanonicalizationMethod instance from an XML string """ - return create_class_from_xml_string(CanonicalizationMethod, xml_string) - - -class SignedInfo(DsBase): - """The ds:SignedInfo element""" - - c_tag = 'SignedInfo' + c_tag = 'SPKISexp' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Id'] = "identifier" - c_children['{%s}CanonicalizationMethod' % NAMESPACE] = ( - 'canonicalization_method', CanonicalizationMethod) - c_children['{%s}SignatureMethod' % NAMESPACE] = ( - 'signature_method', SignatureMethod) - c_children['{%s}Reference' % NAMESPACE] = ('reference', [Reference]) - c_child_order = ['canonicalization_method', 'signature_method', - 'reference'] + c_value_type = 'base64Binary' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - def __init__(self, identifier=None, canonicalization_method=None, - signature_method=None, reference=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for SignedInfo +def spki_sexp_from_string(xml_string): + return saml2.create_class_from_xml_string(SPKISexp, xml_string) - :param identifier: Id attribute - :param canonicalization_method: CanonicalizationMethod element - :param signature_method: SignatureMethod element - :param reference: Reference elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ +class SPKIDataType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:SPKIDataType element """ - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.identifier = identifier - self.canonicalization_method = canonicalization_method - self.signature_method = signature_method - self.reference = reference or [] + c_tag = 'SPKIDataType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}SPKISexp'] = ('spki_sexp', [SPKISexp]) + c_child_order.extend(['spki_sexp']) -def signed_info_from_string(xml_string): - """ Create SignedInfo instance from an XML string """ - return create_class_from_xml_string(SignedInfo, xml_string) + def __init__(self, + spki_sexp=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.spki_sexp=spki_sexp or [] +def spki_data_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SPKIDataType, xml_string) -class SignatureValue(DsBase): - """The ds:SignatureValue element""" +class ObjectType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:ObjectType element """ + + c_tag = 'ObjectType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['Id'] = ('id', 'ID', False) + c_attributes['MimeType'] = ('mime_type', 'string', False) + c_attributes['Encoding'] = ('encoding', 'anyURI', False) + + def __init__(self, + id=None, + mime_type=None, + encoding=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.id=id + self.mime_type=mime_type + self.encoding=encoding + +def object_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ObjectType, xml_string) + +class SignaturePropertyType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:SignaturePropertyType element """ + + c_tag = 'SignaturePropertyType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['Target'] = ('target', 'anyURI', True) + c_attributes['Id'] = ('id', 'ID', False) + + def __init__(self, + target=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.target=target + self.id=id + +def signature_property_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SignaturePropertyType, xml_string) + +class HMACOutputLengthType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:HMACOutputLengthType element """ + + c_tag = 'HMACOutputLengthType' + c_namespace = NAMESPACE + c_value_type = {'base': 'integer'} + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def hmac_output_length_type_from_string(xml_string): + return saml2.create_class_from_xml_string(HMACOutputLengthType, xml_string) + +class P(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:P element """ + + c_tag = 'P' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def p_from_string(xml_string): + return saml2.create_class_from_xml_string(P, xml_string) + +class Q(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:Q element """ + + c_tag = 'Q' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def q_from_string(xml_string): + return saml2.create_class_from_xml_string(Q, xml_string) + +class G(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:G element """ + + c_tag = 'G' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def g_from_string(xml_string): + return saml2.create_class_from_xml_string(G, xml_string) + +class Y(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:Y element """ + + c_tag = 'Y' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def y_from_string(xml_string): + return saml2.create_class_from_xml_string(Y, xml_string) + +class J(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:J element """ + + c_tag = 'J' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def j_from_string(xml_string): + return saml2.create_class_from_xml_string(J, xml_string) + +class Seed(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:Seed element """ + + c_tag = 'Seed' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def seed_from_string(xml_string): + return saml2.create_class_from_xml_string(Seed, xml_string) + +class PgenCounter(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:PgenCounter element """ + + c_tag = 'PgenCounter' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def pgen_counter_from_string(xml_string): + return saml2.create_class_from_xml_string(PgenCounter, xml_string) + +class DSAKeyValueType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:DSAKeyValueType element """ + + c_tag = 'DSAKeyValueType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}P'] = ('p', P) + c_children['{http://www.w3.org/2000/09/xmldsig#}Q'] = ('q', Q) + c_children['{http://www.w3.org/2000/09/xmldsig#}G'] = ('g', G) + c_children['{http://www.w3.org/2000/09/xmldsig#}Y'] = ('y', Y) + c_children['{http://www.w3.org/2000/09/xmldsig#}J'] = ('j', J) + c_children['{http://www.w3.org/2000/09/xmldsig#}Seed'] = ('seed', Seed) + c_children['{http://www.w3.org/2000/09/xmldsig#}PgenCounter'] = ('pgen_counter', PgenCounter) + c_child_order.extend(['p', 'q', 'g', 'y', 'j', 'seed', 'pgen_counter']) + + def __init__(self, + p=None, + q=None, + g=None, + y=None, + j=None, + seed=None, + pgen_counter=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.p=p + self.q=q + self.g=g + self.y=y + self.j=j + self.seed=seed + self.pgen_counter=pgen_counter + +def dsa_key_value_type_from_string(xml_string): + return saml2.create_class_from_xml_string(DSAKeyValueType, xml_string) + +class Modulus(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:Modulus element """ + + c_tag = 'Modulus' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def modulus_from_string(xml_string): + return saml2.create_class_from_xml_string(Modulus, xml_string) + +class Exponent(CryptoBinary): + """The http://www.w3.org/2000/09/xmldsig#:Exponent element """ + + c_tag = 'Exponent' + c_namespace = NAMESPACE + c_children = CryptoBinary.c_children.copy() + c_attributes = CryptoBinary.c_attributes.copy() + c_child_order = CryptoBinary.c_child_order[:] + +def exponent_from_string(xml_string): + return saml2.create_class_from_xml_string(Exponent, xml_string) + +class RSAKeyValueType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:RSAKeyValueType element """ + + c_tag = 'RSAKeyValueType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Modulus'] = ('modulus', Modulus) + c_children['{http://www.w3.org/2000/09/xmldsig#}Exponent'] = ('exponent', Exponent) + c_child_order.extend(['modulus', 'exponent']) + + def __init__(self, + modulus=None, + exponent=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.modulus=modulus + self.exponent=exponent + +def rsa_key_value_type_from_string(xml_string): + return saml2.create_class_from_xml_string(RSAKeyValueType, xml_string) + +class SignatureValue(SignatureValueType): + """The http://www.w3.org/2000/09/xmldsig#:SignatureValue element """ c_tag = 'SignatureValue' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Id'] = "identifier" - - def __init__(self, identifier=None, text=None, extension_elements=None, - extension_attributes=None): - """Constructor for SignatureValue - - Args: - :param identifier: Id attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.identifier = identifier + c_children = SignatureValueType.c_children.copy() + c_attributes = SignatureValueType.c_attributes.copy() + c_child_order = SignatureValueType.c_child_order[:] def signature_value_from_string(xml_string): - """ Create SignatureValue instance from an XML string """ - return create_class_from_xml_string(SignatureValue, xml_string) + return saml2.create_class_from_xml_string(SignatureValue, xml_string) +class CanonicalizationMethod(CanonicalizationMethodType): + """The http://www.w3.org/2000/09/xmldsig#:CanonicalizationMethod element """ -class Signature(DsBase): - """The ds:Signature element""" + c_tag = 'CanonicalizationMethod' + c_namespace = NAMESPACE + c_children = CanonicalizationMethodType.c_children.copy() + c_attributes = CanonicalizationMethodType.c_attributes.copy() + c_child_order = CanonicalizationMethodType.c_child_order[:] + +def canonicalization_method_from_string(xml_string): + return saml2.create_class_from_xml_string(CanonicalizationMethod, xml_string) + +class HMACOutputLength(HMACOutputLengthType): + """The http://www.w3.org/2000/09/xmldsig#:HMACOutputLength element """ + + c_tag = 'HMACOutputLength' + c_namespace = NAMESPACE + c_children = HMACOutputLengthType.c_children.copy() + c_attributes = HMACOutputLengthType.c_attributes.copy() + c_child_order = HMACOutputLengthType.c_child_order[:] + +def hmac_output_length_from_string(xml_string): + return saml2.create_class_from_xml_string(HMACOutputLength, xml_string) + +class SignatureMethodType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:SignatureMethodType element """ + + c_tag = 'SignatureMethodType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}HMACOutputLength'] = ('hmac_output_length', HMACOutputLength) + c_attributes['Algorithm'] = ('algorithm', 'anyURI', True) + c_child_order.extend(['hmac_output_length']) + + def __init__(self, + hmac_output_length=None, + algorithm=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.hmac_output_length=hmac_output_length + self.algorithm=algorithm + +def signature_method_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SignatureMethodType, xml_string) + +class Transform(TransformType): + """The http://www.w3.org/2000/09/xmldsig#:Transform element """ + + c_tag = 'Transform' + c_namespace = NAMESPACE + c_children = TransformType.c_children.copy() + c_attributes = TransformType.c_attributes.copy() + c_child_order = TransformType.c_child_order[:] + +def transform_from_string(xml_string): + return saml2.create_class_from_xml_string(Transform, xml_string) + +class DigestMethod(DigestMethodType): + """The http://www.w3.org/2000/09/xmldsig#:DigestMethod element """ + + c_tag = 'DigestMethod' + c_namespace = NAMESPACE + c_children = DigestMethodType.c_children.copy() + c_attributes = DigestMethodType.c_attributes.copy() + c_child_order = DigestMethodType.c_child_order[:] + +def digest_method_from_string(xml_string): + return saml2.create_class_from_xml_string(DigestMethod, xml_string) + +class DigestValue(DigestValueType): + """The http://www.w3.org/2000/09/xmldsig#:DigestValue element """ + + c_tag = 'DigestValue' + c_namespace = NAMESPACE + c_children = DigestValueType.c_children.copy() + c_attributes = DigestValueType.c_attributes.copy() + c_child_order = DigestValueType.c_child_order[:] + +def digest_value_from_string(xml_string): + return saml2.create_class_from_xml_string(DigestValue, xml_string) + +class X509IssuerSerial(X509IssuerSerialType): + """The http://www.w3.org/2000/09/xmldsig#:X509IssuerSerial element """ + + c_tag = 'X509IssuerSerial' + c_namespace = NAMESPACE + c_children = X509IssuerSerialType.c_children.copy() + c_attributes = X509IssuerSerialType.c_attributes.copy() + c_child_order = X509IssuerSerialType.c_child_order[:] + +def x509_issuer_serial_from_string(xml_string): + return saml2.create_class_from_xml_string(X509IssuerSerial, xml_string) + +class X509SKI(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:X509SKI element """ + + c_tag = 'X509SKI' + c_namespace = NAMESPACE + c_value_type = 'base64Binary' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def x509_ski_from_string(xml_string): + return saml2.create_class_from_xml_string(X509SKI, xml_string) + +class X509SubjectName(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:X509SubjectName element """ + + c_tag = 'X509SubjectName' + c_namespace = NAMESPACE + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def x509_subject_name_from_string(xml_string): + return saml2.create_class_from_xml_string(X509SubjectName, xml_string) + +class X509Certificate(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:X509Certificate element """ + + c_tag = 'X509Certificate' + c_namespace = NAMESPACE + c_value_type = 'base64Binary' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def x509_certificate_from_string(xml_string): + return saml2.create_class_from_xml_string(X509Certificate, xml_string) + +class X509CRL(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:X509CRL element """ + + c_tag = 'X509CRL' + c_namespace = NAMESPACE + c_value_type = 'base64Binary' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def x509_crl_from_string(xml_string): + return saml2.create_class_from_xml_string(X509CRL, xml_string) + +class X509DataType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:X509DataType element """ + + c_tag = 'X509DataType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}X509IssuerSerial'] = ('x509_issuer_serial', [X509IssuerSerial]) + c_children['{http://www.w3.org/2000/09/xmldsig#}X509SKI'] = ('x509_ski', [X509SKI]) + c_children['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'] = ('x509_subject_name', [X509SubjectName]) + c_children['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'] = ('x509_certificate', [X509Certificate]) + c_children['{http://www.w3.org/2000/09/xmldsig#}X509CRL'] = ('x509_crl', [X509CRL]) + c_child_order.extend(['x509_issuer_serial', 'x509_ski', 'x509_subject_name', 'x509_certificate', 'x509_crl']) + + def __init__(self, + x509_issuer_serial=None, + x509_ski=None, + x509_subject_name=None, + x509_certificate=None, + x509_crl=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.x509_issuer_serial=x509_issuer_serial or [] + self.x509_ski=x509_ski or [] + self.x509_subject_name=x509_subject_name or [] + self.x509_certificate=x509_certificate or [] + self.x509_crl=x509_crl or [] + +def x509_data_type_from_string(xml_string): + return saml2.create_class_from_xml_string(X509DataType, xml_string) + +class PGPData(PGPDataType): + """The http://www.w3.org/2000/09/xmldsig#:PGPData element """ + + c_tag = 'PGPData' + c_namespace = NAMESPACE + c_children = PGPDataType.c_children.copy() + c_attributes = PGPDataType.c_attributes.copy() + c_child_order = PGPDataType.c_child_order[:] + +def pgp_data_from_string(xml_string): + return saml2.create_class_from_xml_string(PGPData, xml_string) + +class SPKIData(SPKIDataType): + """The http://www.w3.org/2000/09/xmldsig#:SPKIData element """ + + c_tag = 'SPKIData' + c_namespace = NAMESPACE + c_children = SPKIDataType.c_children.copy() + c_attributes = SPKIDataType.c_attributes.copy() + c_child_order = SPKIDataType.c_child_order[:] + +def spki_data_from_string(xml_string): + return saml2.create_class_from_xml_string(SPKIData, xml_string) + +class Object(ObjectType): + """The http://www.w3.org/2000/09/xmldsig#:Object element """ + + c_tag = 'Object' + c_namespace = NAMESPACE + c_children = ObjectType.c_children.copy() + c_attributes = ObjectType.c_attributes.copy() + c_child_order = ObjectType.c_child_order[:] + +def object_from_string(xml_string): + return saml2.create_class_from_xml_string(Object, xml_string) + +class SignatureProperty(SignaturePropertyType): + """The http://www.w3.org/2000/09/xmldsig#:SignatureProperty element """ + + c_tag = 'SignatureProperty' + c_namespace = NAMESPACE + c_children = SignaturePropertyType.c_children.copy() + c_attributes = SignaturePropertyType.c_attributes.copy() + c_child_order = SignaturePropertyType.c_child_order[:] + +def signature_property_from_string(xml_string): + return saml2.create_class_from_xml_string(SignatureProperty, xml_string) + +class DSAKeyValue(DSAKeyValueType): + """The http://www.w3.org/2000/09/xmldsig#:DSAKeyValue element """ + + c_tag = 'DSAKeyValue' + c_namespace = NAMESPACE + c_children = DSAKeyValueType.c_children.copy() + c_attributes = DSAKeyValueType.c_attributes.copy() + c_child_order = DSAKeyValueType.c_child_order[:] + +def dsa_key_value_from_string(xml_string): + return saml2.create_class_from_xml_string(DSAKeyValue, xml_string) + +class RSAKeyValue(RSAKeyValueType): + """The http://www.w3.org/2000/09/xmldsig#:RSAKeyValue element """ + + c_tag = 'RSAKeyValue' + c_namespace = NAMESPACE + c_children = RSAKeyValueType.c_children.copy() + c_attributes = RSAKeyValueType.c_attributes.copy() + c_child_order = RSAKeyValueType.c_child_order[:] + +def rsa_key_value_from_string(xml_string): + return saml2.create_class_from_xml_string(RSAKeyValue, xml_string) + +class SignatureMethod(SignatureMethodType): + """The http://www.w3.org/2000/09/xmldsig#:SignatureMethod element """ + + c_tag = 'SignatureMethod' + c_namespace = NAMESPACE + c_children = SignatureMethodType.c_children.copy() + c_attributes = SignatureMethodType.c_attributes.copy() + c_child_order = SignatureMethodType.c_child_order[:] + +def signature_method_from_string(xml_string): + return saml2.create_class_from_xml_string(SignatureMethod, xml_string) + +class TransformsType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:TransformsType element """ + + c_tag = 'TransformsType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Transform'] = ('transform', [Transform]) + c_child_order.extend(['transform']) + + def __init__(self, + transform=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.transform=transform or [] + +def transforms_type_from_string(xml_string): + return saml2.create_class_from_xml_string(TransformsType, xml_string) + +class KeyValueType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:KeyValueType element """ + + c_tag = 'KeyValueType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}DSAKeyValue'] = ('dsa_key_value', DSAKeyValue) + c_children['{http://www.w3.org/2000/09/xmldsig#}RSAKeyValue'] = ('rsa_key_value', RSAKeyValue) + c_child_order.extend(['dsa_key_value', 'rsa_key_value']) + + def __init__(self, + dsa_key_value=None, + rsa_key_value=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.dsa_key_value=dsa_key_value + self.rsa_key_value=rsa_key_value + +def key_value_type_from_string(xml_string): + return saml2.create_class_from_xml_string(KeyValueType, xml_string) + +class X509Data(X509DataType): + """The http://www.w3.org/2000/09/xmldsig#:X509Data element """ + + c_tag = 'X509Data' + c_namespace = NAMESPACE + c_children = X509DataType.c_children.copy() + c_attributes = X509DataType.c_attributes.copy() + c_child_order = X509DataType.c_child_order[:] + +def x509_data_from_string(xml_string): + return saml2.create_class_from_xml_string(X509Data, xml_string) + +class SignaturePropertiesType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:SignaturePropertiesType element """ + + c_tag = 'SignaturePropertiesType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}SignatureProperty'] = ('signature_property', [SignatureProperty]) + c_attributes['Id'] = ('id', 'ID', False) + c_child_order.extend(['signature_property']) + + def __init__(self, + signature_property=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.signature_property=signature_property or [] + self.id=id + +def signature_properties_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SignaturePropertiesType, xml_string) + +class Transforms(TransformsType): + """The http://www.w3.org/2000/09/xmldsig#:Transforms element """ + + c_tag = 'Transforms' + c_namespace = NAMESPACE + c_children = TransformsType.c_children.copy() + c_attributes = TransformsType.c_attributes.copy() + c_child_order = TransformsType.c_child_order[:] + +def transforms_from_string(xml_string): + return saml2.create_class_from_xml_string(Transforms, xml_string) + +class KeyValue(KeyValueType): + """The http://www.w3.org/2000/09/xmldsig#:KeyValue element """ + + c_tag = 'KeyValue' + c_namespace = NAMESPACE + c_children = KeyValueType.c_children.copy() + c_attributes = KeyValueType.c_attributes.copy() + c_child_order = KeyValueType.c_child_order[:] + +def key_value_from_string(xml_string): + return saml2.create_class_from_xml_string(KeyValue, xml_string) + +class RetrievalMethodType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:RetrievalMethodType element """ + + c_tag = 'RetrievalMethodType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Transforms'] = ('transforms', Transforms) + c_attributes['URI'] = ('uri', 'anyURI', False) + c_attributes['Type'] = ('type', 'anyURI', False) + c_child_order.extend(['transforms']) + + def __init__(self, + transforms=None, + uri=None, + type=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.transforms=transforms + self.uri=uri + self.type=type + +def retrieval_method_type_from_string(xml_string): + return saml2.create_class_from_xml_string(RetrievalMethodType, xml_string) + +class SignatureProperties(SignaturePropertiesType): + """The http://www.w3.org/2000/09/xmldsig#:SignatureProperties element """ + + c_tag = 'SignatureProperties' + c_namespace = NAMESPACE + c_children = SignaturePropertiesType.c_children.copy() + c_attributes = SignaturePropertiesType.c_attributes.copy() + c_child_order = SignaturePropertiesType.c_child_order[:] + +def signature_properties_from_string(xml_string): + return saml2.create_class_from_xml_string(SignatureProperties, xml_string) + +class ReferenceType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:ReferenceType element """ + + c_tag = 'ReferenceType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Transforms'] = ('transforms', Transforms) + c_children['{http://www.w3.org/2000/09/xmldsig#}DigestMethod'] = ('digest_method', DigestMethod) + c_children['{http://www.w3.org/2000/09/xmldsig#}DigestValue'] = ('digest_value', DigestValue) + c_attributes['Id'] = ('id', 'ID', False) + c_attributes['URI'] = ('uri', 'anyURI', False) + c_attributes['Type'] = ('type', 'anyURI', False) + c_child_order.extend(['transforms', 'digest_method', 'digest_value']) + + def __init__(self, + transforms=None, + digest_method=None, + digest_value=None, + id=None, + uri=None, + type=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.transforms=transforms + self.digest_method=digest_method + self.digest_value=digest_value + self.id=id + self.uri=uri + self.type=type + +def reference_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ReferenceType, xml_string) + +class RetrievalMethod(RetrievalMethodType): + """The http://www.w3.org/2000/09/xmldsig#:RetrievalMethod element """ + + c_tag = 'RetrievalMethod' + c_namespace = NAMESPACE + c_children = RetrievalMethodType.c_children.copy() + c_attributes = RetrievalMethodType.c_attributes.copy() + c_child_order = RetrievalMethodType.c_child_order[:] + +def retrieval_method_from_string(xml_string): + return saml2.create_class_from_xml_string(RetrievalMethod, xml_string) + +class Reference(ReferenceType): + """The http://www.w3.org/2000/09/xmldsig#:Reference element """ + + c_tag = 'Reference' + c_namespace = NAMESPACE + c_children = ReferenceType.c_children.copy() + c_attributes = ReferenceType.c_attributes.copy() + c_child_order = ReferenceType.c_child_order[:] + +def reference_from_string(xml_string): + return saml2.create_class_from_xml_string(Reference, xml_string) + +class KeyInfoType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:KeyInfoType element """ + + c_tag = 'KeyInfoType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}KeyName'] = ('key_name', [KeyName]) + c_children['{http://www.w3.org/2000/09/xmldsig#}KeyValue'] = ('key_value', [KeyValue]) + c_children['{http://www.w3.org/2000/09/xmldsig#}RetrievalMethod'] = ('retrieval_method', [RetrievalMethod]) + c_children['{http://www.w3.org/2000/09/xmldsig#}X509Data'] = ('x509_data', [X509Data]) + c_children['{http://www.w3.org/2000/09/xmldsig#}PGPData'] = ('pgp_data', [PGPData]) + c_children['{http://www.w3.org/2000/09/xmldsig#}SPKIData'] = ('spki_data', [SPKIData]) + c_children['{http://www.w3.org/2000/09/xmldsig#}MgmtData'] = ('mgmt_data', [MgmtData]) + c_attributes['Id'] = ('id', 'ID', False) + c_child_order.extend(['key_name', 'key_value', 'retrieval_method', 'x509_data', 'pgp_data', 'spki_data', 'mgmt_data']) + + def __init__(self, + key_name=None, + key_value=None, + retrieval_method=None, + x509_data=None, + pgp_data=None, + spki_data=None, + mgmt_data=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.key_name=key_name or [] + self.key_value=key_value or [] + self.retrieval_method=retrieval_method or [] + self.x509_data=x509_data or [] + self.pgp_data=pgp_data or [] + self.spki_data=spki_data or [] + self.mgmt_data=mgmt_data or [] + self.id=id + +def key_info_type_from_string(xml_string): + return saml2.create_class_from_xml_string(KeyInfoType, xml_string) + +class ManifestType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:ManifestType element """ + + c_tag = 'ManifestType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Reference'] = ('reference', [Reference]) + c_attributes['Id'] = ('id', 'ID', False) + c_child_order.extend(['reference']) + + def __init__(self, + reference=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.reference=reference or [] + self.id=id + +def manifest_type_from_string(xml_string): + return saml2.create_class_from_xml_string(ManifestType, xml_string) + +class SignedInfoType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:SignedInfoType element """ + + c_tag = 'SignedInfoType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}CanonicalizationMethod'] = ('canonicalization_method', CanonicalizationMethod) + c_children['{http://www.w3.org/2000/09/xmldsig#}SignatureMethod'] = ('signature_method', SignatureMethod) + c_children['{http://www.w3.org/2000/09/xmldsig#}Reference'] = ('reference', [Reference]) + c_attributes['Id'] = ('id', 'ID', False) + c_child_order.extend(['canonicalization_method', 'signature_method', 'reference']) + + def __init__(self, + canonicalization_method=None, + signature_method=None, + reference=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.canonicalization_method=canonicalization_method + self.signature_method=signature_method + self.reference=reference or [] + self.id=id + +def signed_info_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SignedInfoType, xml_string) + +class KeyInfo(KeyInfoType): + """The http://www.w3.org/2000/09/xmldsig#:KeyInfo element """ + + c_tag = 'KeyInfo' + c_namespace = NAMESPACE + c_children = KeyInfoType.c_children.copy() + c_attributes = KeyInfoType.c_attributes.copy() + c_child_order = KeyInfoType.c_child_order[:] + +def key_info_from_string(xml_string): + return saml2.create_class_from_xml_string(KeyInfo, xml_string) + +class Manifest(ManifestType): + """The http://www.w3.org/2000/09/xmldsig#:Manifest element """ + + c_tag = 'Manifest' + c_namespace = NAMESPACE + c_children = ManifestType.c_children.copy() + c_attributes = ManifestType.c_attributes.copy() + c_child_order = ManifestType.c_child_order[:] + +def manifest_from_string(xml_string): + return saml2.create_class_from_xml_string(Manifest, xml_string) + +class SignedInfo(SignedInfoType): + """The http://www.w3.org/2000/09/xmldsig#:SignedInfo element """ + + c_tag = 'SignedInfo' + c_namespace = NAMESPACE + c_children = SignedInfoType.c_children.copy() + c_attributes = SignedInfoType.c_attributes.copy() + c_child_order = SignedInfoType.c_child_order[:] + +def signed_info_from_string(xml_string): + return saml2.create_class_from_xml_string(SignedInfo, xml_string) + +class SignatureType(SamlBase): + """The http://www.w3.org/2000/09/xmldsig#:SignatureType element """ + + c_tag = 'SignatureType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}SignedInfo'] = ('signed_info', SignedInfo) + c_children['{http://www.w3.org/2000/09/xmldsig#}SignatureValue'] = ('signature_value', SignatureValue) + c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', KeyInfo) + c_children['{http://www.w3.org/2000/09/xmldsig#}Object'] = ('object', [Object]) + c_attributes['Id'] = ('id', 'ID', False) + c_child_order.extend(['signed_info', 'signature_value', 'key_info', 'object']) + + def __init__(self, + signed_info=None, + signature_value=None, + key_info=None, + object=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.signed_info=signed_info + self.signature_value=signature_value + self.key_info=key_info + self.object=object or [] + self.id=id + +def signature_type_from_string(xml_string): + return saml2.create_class_from_xml_string(SignatureType, xml_string) + +class Signature(SignatureType): + """The http://www.w3.org/2000/09/xmldsig#:Signature element """ c_tag = 'Signature' c_namespace = NAMESPACE - c_children = DsBase.c_children.copy() - c_attributes = DsBase.c_attributes.copy() - c_attributes['Id'] = "id" - c_children['{%s}SignedInfo' % NAMESPACE] = ('signed_info', SignedInfo) - c_children['{%s}SignatureValue' % NAMESPACE] = ( - 'signature_value', SignatureValue) - c_children['{%s}KeyInfo' % NAMESPACE] = ('key_info', KeyInfo) - c_children['{%s}Object' % NAMESPACE] = ('object', [Object]) - c_child_order = ["signed_info", "signature_value", "key_info", "object"] - - def __init__(self, id=None, signed_info=None, signature_value=None, - key_info=None, objects=None, text=None, - extension_elements=None, extension_attributes=None): - """Constructor for Signature - - :param identifier: Id attribute - :param signed_info: SignedInfo element - :param signature_value: SignatureValue element - :param key_info: KeyInfo element - :param object: Object elements - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string pairs - """ - - DsBase.__init__(self, text, extension_elements, extension_attributes) - self.id = id - self.signed_info = signed_info - self.signature_value = signature_value - self.key_info = key_info - self.object = objects or [] - + c_children = SignatureType.c_children.copy() + c_attributes = SignatureType.c_attributes.copy() + c_child_order = SignatureType.c_child_order[:] def signature_from_string(xml_string): - """ Create Signature instance from an XML string """ - return create_class_from_xml_string(Signature, xml_string) - - -def get_empty_signature(canonicalization_method_algorithm=C14N_WITH_C, - signature_method_algorithm=SIG_RSA_SHA1, - transform_algorithm=TRANSFORM_ENVELOPED, - digest_algorithm=DIGEST_SHA1): - - canonicalization_method = CanonicalizationMethod( - algorithm=canonicalization_method_algorithm) - signature_method = SignatureMethod(algorithm=signature_method_algorithm) - transforms = Transforms(transform=Transform(algorithm=transform_algorithm)) - digest_method = DigestMethod(algorithm=digest_algorithm) - reference = Reference(uri="", transforms=transforms, - digest_method=digest_method, - digest_value=DigestValue()) - signed_info = SignedInfo( - canonicalization_method=canonicalization_method, - signature_method=signature_method, - reference=reference) - signature = Signature(signed_info=signed_info, - signature_value=SignatureValue(), - key_info=KeyInfo(key_value=KeyValue())) - return signature - + return saml2.create_class_from_xml_string(Signature, xml_string) ELEMENT_FROM_STRING = { - Object.c_tag: object_from_string, - MgmtData.c_tag: mgmt_data_from_string, - SPKISexp.c_tag: spki_sexp_from_string, - SPKIData.c_tag: spki_data_from_string, - PGPKeyID.c_tag: pgp_key_id_from_string, - PGPKeyPacket.c_tag: pgp_key_packet_from_string, - PGPData.c_tag: pgp_data_from_string, - X509IssuerName.c_tag: x509_issuer_name_from_string, - X509IssuerNumber.c_tag: x509_issuer_number_from_string, - X509IssuerSerial.c_tag: x509_issuer_serial_from_string, - X509SKI.c_tag: x509_ski_from_string, - X509SubjectName.c_tag: x509_subject_name_from_string, - X509Certificate.c_tag: x509_certificate_from_string, - X509CRL.c_tag: x509_crl_from_string, - X509Data.c_tag: x509_data_from_string, - XPath.c_tag: xpath_from_string, - Transform.c_tag: transform_from_string, - Transforms.c_tag: transforms_from_string, - RetrievalMethod.c_tag: retrieval_method_from_string, - Modulus.c_tag: modulus_from_string, - Exponent.c_tag: exponent_from_string, - RSAKeyValue.c_tag: rsa_key_value_from_string, - DsP.c_tag: p_from_string, - DsQ.c_tag: q_from_string, - DsG.c_tag: g_from_string, - DsY.c_tag: y_from_string, - DsJ.c_tag: j_from_string, - Seed.c_tag: seed_from_string, - PgenCounter.c_tag: pgen_counter_from_string, - DSAKeyValue.c_tag: dsa_key_value_from_string, - KeyValue.c_tag: key_value_from_string, - KeyName.c_tag: key_name_from_string, - KeyInfo.c_tag: key_info_from_string, - DigestValue.c_tag: digest_value_from_string, - DigestMethod.c_tag: digest_method_from_string, - Reference.c_tag: reference_from_string, - HMACOutputLength.c_tag: hmac_output_length_from_string, - SignatureMethod.c_tag: signature_method_from_string, - CanonicalizationMethod.c_tag: canonicalization_method_from_string, - SignedInfo.c_tag: signed_info_from_string, - SignatureValue.c_tag: signature_value_from_string, + CryptoBinary.c_tag: crypto_binary_from_string, Signature.c_tag: signature_from_string, + SignatureType.c_tag: signature_type_from_string, + SignatureValue.c_tag: signature_value_from_string, + SignatureValueType.c_tag: signature_value_type_from_string, + SignedInfo.c_tag: signed_info_from_string, + SignedInfoType.c_tag: signed_info_type_from_string, + CanonicalizationMethod.c_tag: canonicalization_method_from_string, + CanonicalizationMethodType.c_tag: canonicalization_method_type_from_string, + SignatureMethod.c_tag: signature_method_from_string, + SignatureMethodType.c_tag: signature_method_type_from_string, + Reference.c_tag: reference_from_string, + ReferenceType.c_tag: reference_type_from_string, + Transforms.c_tag: transforms_from_string, + TransformsType.c_tag: transforms_type_from_string, + Transform.c_tag: transform_from_string, + TransformType.c_tag: transform_type_from_string, + DigestMethod.c_tag: digest_method_from_string, + DigestMethodType.c_tag: digest_method_type_from_string, + DigestValue.c_tag: digest_value_from_string, + DigestValueType.c_tag: digest_value_type_from_string, + KeyInfo.c_tag: key_info_from_string, + KeyInfoType.c_tag: key_info_type_from_string, + KeyName.c_tag: key_name_from_string, + MgmtData.c_tag: mgmt_data_from_string, + KeyValue.c_tag: key_value_from_string, + KeyValueType.c_tag: key_value_type_from_string, + RetrievalMethod.c_tag: retrieval_method_from_string, + RetrievalMethodType.c_tag: retrieval_method_type_from_string, + X509Data.c_tag: x509_data_from_string, + X509DataType.c_tag: x509_data_type_from_string, + X509IssuerSerialType.c_tag: x509_issuer_serial_type_from_string, + PGPData.c_tag: pgp_data_from_string, + PGPDataType.c_tag: pgp_data_type_from_string, + SPKIData.c_tag: spki_data_from_string, + SPKIDataType.c_tag: spki_data_type_from_string, + Object.c_tag: object_from_string, + ObjectType.c_tag: object_type_from_string, + Manifest.c_tag: manifest_from_string, + ManifestType.c_tag: manifest_type_from_string, + SignatureProperties.c_tag: signature_properties_from_string, + SignaturePropertiesType.c_tag: signature_properties_type_from_string, + SignatureProperty.c_tag: signature_property_from_string, + SignaturePropertyType.c_tag: signature_property_type_from_string, + HMACOutputLengthType.c_tag: hmac_output_length_type_from_string, + DSAKeyValue.c_tag: dsa_key_value_from_string, + DSAKeyValueType.c_tag: dsa_key_value_type_from_string, + RSAKeyValue.c_tag: rsa_key_value_from_string, + RSAKeyValueType.c_tag: rsa_key_value_type_from_string, } + +ELEMENT_BY_TAG = { + 'CryptoBinary': CryptoBinary, + 'Signature': Signature, + 'SignatureType': SignatureType, + 'SignatureValue': SignatureValue, + 'SignatureValueType': SignatureValueType, + 'SignedInfo': SignedInfo, + 'SignedInfoType': SignedInfoType, + 'CanonicalizationMethod': CanonicalizationMethod, + 'CanonicalizationMethodType': CanonicalizationMethodType, + 'SignatureMethod': SignatureMethod, + 'SignatureMethodType': SignatureMethodType, + 'Reference': Reference, + 'ReferenceType': ReferenceType, + 'Transforms': Transforms, + 'TransformsType': TransformsType, + 'Transform': Transform, + 'TransformType': TransformType, + 'DigestMethod': DigestMethod, + 'DigestMethodType': DigestMethodType, + 'DigestValue': DigestValue, + 'DigestValueType': DigestValueType, + 'KeyInfo': KeyInfo, + 'KeyInfoType': KeyInfoType, + 'KeyName': KeyName, + 'MgmtData': MgmtData, + 'KeyValue': KeyValue, + 'KeyValueType': KeyValueType, + 'RetrievalMethod': RetrievalMethod, + 'RetrievalMethodType': RetrievalMethodType, + 'X509Data': X509Data, + 'X509DataType': X509DataType, + 'X509IssuerSerialType': X509IssuerSerialType, + 'PGPData': PGPData, + 'PGPDataType': PGPDataType, + 'SPKIData': SPKIData, + 'SPKIDataType': SPKIDataType, + 'Object': Object, + 'ObjectType': ObjectType, + 'Manifest': Manifest, + 'ManifestType': ManifestType, + 'SignatureProperties': SignatureProperties, + 'SignaturePropertiesType': SignaturePropertiesType, + 'SignatureProperty': SignatureProperty, + 'SignaturePropertyType': SignaturePropertyType, + 'HMACOutputLengthType': HMACOutputLengthType, + 'DSAKeyValue': DSAKeyValue, + 'DSAKeyValueType': DSAKeyValueType, + 'RSAKeyValue': RSAKeyValue, + 'RSAKeyValueType': RSAKeyValueType, +} + +def factory(tag, **kwargs): + return ELEMENT_BY_TAG[tag](**kwargs) + diff --git a/src/xmlenc/__init__.py b/src/xmlenc/__init__.py index 05e2d1e..dcddad0 100644 --- a/src/xmlenc/__init__.py +++ b/src/xmlenc/__init__.py @@ -1,568 +1,675 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- +#!/usr/bin/env python + # -# Copyright (C) 2009 Umea Universitet. +# Generated Thu Jul 15 20:59:30 2010 by parse_xsd.py version 0.3. # -# 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. -"""Contains classes representing xmlenc elements. - - Module objective: provide data classes for xmlenc constructs. These - classes hide the XML-ness of Saml and provide a set of native Python - classes to interact with. - - Classes in this module inherits saml.SamlBase now. - -""" - -try: - from xml.etree import cElementTree as ElementTree -except ImportError: - try: - import cElementTree as ElementTree - except ImportError: - from elementtree import ElementTree - import saml2 -from saml2 import create_class_from_xml_string +from saml2 import SamlBase import xmldsig as ds NAMESPACE = 'http://www.w3.org/2001/04/xmlenc#' -#TEMPLATE = '{http://www.w3.org/2001/04/xmlenc#}%s' -class EncBase(saml2.SamlBase): - """The enc:EncBase element""" +class KeySizeType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:KeySizeType element """ - c_children = {} - c_attributes = {} - -# --------------------------------------------------------------------------- -# KeySize -# --------------------------------------------------------------------------- - -class KeySize(EncBase): - - c_tag = 'KeySize' + c_tag = 'KeySizeType' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() + c_value_type = {'base': 'integer'} + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] -def key_size_from_string(xml_string): - """ Create KeySize instance from an XML string """ - return create_class_from_xml_string(KeySize, xml_string) +def key_size_type_from_string(xml_string): + return saml2.create_class_from_xml_string(KeySizeType, xml_string) -# --------------------------------------------------------------------------- -# OAEPparams -# --------------------------------------------------------------------------- +class TransformsType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:TransformsType element """ -class OAEPparams(EncBase): - - c_tag = 'OAEPparams' + c_tag = 'TransformsType' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2000/09/xmldsig#}Transform'] = ('transform', [ds.Transform]) + c_child_order.extend(['transform']) -def oaep_params_from_string(xml_string): - """ Create OAEPparams instance from an XML string """ - return create_class_from_xml_string(OAEPparams, xml_string) + def __init__(self, + transform=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.transform=transform or [] -# --------------------------------------------------------------------------- -# EncryptionMethod -# --------------------------------------------------------------------------- +def transforms_type_from_string(xml_string): + return saml2.create_class_from_xml_string(TransformsType, xml_string) -class EncryptionMethod(EncBase): - """The enc:EncryptionMethod element""" +class KA_Nonce(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:KA_Nonce element """ - c_tag = 'EncryptionMethod' + c_tag = 'KA_Nonce' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_attributes['Algorithm'] = 'algorithm' - c_children['{%s}KeySize' % NAMESPACE] = ( - 'key_size', [KeySize]) - c_children['{%s}OAEPparams' % NAMESPACE] = ( - 'oaep_params', [OAEPparams]) + c_value_type = 'base64Binary' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] - def __init__(self, algorithm=None, key_size=None, oaep_params=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for EncryptedType +def k_a__nonce_from_string(xml_string): + return saml2.create_class_from_xml_string(KA_Nonce, xml_string) - :param algorithm: Algorithm attribute - :param key_size: KeySize attribute - :param oaep_params: OAEPparams attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +class OriginatorKeyInfo(ds.KeyInfoType): + """The http://www.w3.org/2001/04/xmlenc#:OriginatorKeyInfo element """ - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.algorithm = algorithm - self.key_size = key_size - self.oaep_params = oaep_params - -def encryption_method_from_string(xml_string): - """ Create EncryptionMethod instance from an XML string """ - return create_class_from_xml_string(EncryptionMethod, xml_string) - -# --------------------------------------------------------------------------- -# CipherValue -# --------------------------------------------------------------------------- - -class CipherValue(EncBase): - - c_tag = 'CipherValue' + c_tag = 'OriginatorKeyInfo' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() + c_children = ds.KeyInfoType.c_children.copy() + c_attributes = ds.KeyInfoType.c_attributes.copy() + c_child_order = ds.KeyInfoType.c_child_order[:] -def cipher_value_from_string(xml_string): - """ Create CipherValue instance from an XML string """ - return create_class_from_xml_string(CipherValue, xml_string) +def originator_key_info_from_string(xml_string): + return saml2.create_class_from_xml_string(OriginatorKeyInfo, xml_string) -# --------------------------------------------------------------------------- -# Transforms -# NOTICE: There is an element in ds that is also named Transforms, with a very -# similar definition. Confusing!!! -# --------------------------------------------------------------------------- +class RecipientKeyInfo(ds.KeyInfoType): + """The http://www.w3.org/2001/04/xmlenc#:RecipientKeyInfo element """ -class Transforms(EncBase): - - c_tag = 'Transforms' + c_tag = 'RecipientKeyInfo' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_children['{%s}Transform' % ds.NAMESPACE] = ( - 'transform', [ds.Transform]) + c_children = ds.KeyInfoType.c_children.copy() + c_attributes = ds.KeyInfoType.c_attributes.copy() + c_child_order = ds.KeyInfoType.c_child_order[:] - def __init__(self, transform=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for Transforms +def recipient_key_info_from_string(xml_string): + return saml2.create_class_from_xml_string(RecipientKeyInfo, xml_string) - :param transform: Transform element - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +class AgreementMethodType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:AgreementMethodType element """ - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.transform = transform or [] - -def transforms_from_string(xml_string): - """ Create Transforms instance from an XML string """ - return create_class_from_xml_string(Transforms, xml_string) - -# --------------------------------------------------------------------------- -# CipherReference -# --------------------------------------------------------------------------- - -class CipherReference(EncBase): - - c_tag = 'CipherReference' + c_tag = 'AgreementMethodType' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_attributes['URI'] = 'uri' - c_children['{%s}Transforms' % NAMESPACE] = ( - 'transforms', [Transforms]) - - def __init__(self, uri=None, transforms=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for CipherReference + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}KA_Nonce'] = ('k_a__nonce', KA_Nonce) + c_children['{http://www.w3.org/2000/09/xmldsig#}OriginatorKeyInfo'] = ('originator_key_info', ds.KeyInfoType) + c_children['{http://www.w3.org/2000/09/xmldsig#}RecipientKeyInfo'] = ('recipient_key_info', ds.KeyInfoType) + c_attributes['Algorithm'] = ('algorithm', 'anyURI', True) + c_child_order.extend(['k_a__nonce', 'originator_key_info', 'recipient_key_info']) - :param uri: URI attribute - :param transforms: Transforms attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ + def __init__(self, + k_a__nonce=None, + originator_key_info=None, + recipient_key_info=None, + algorithm=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.k_a__nonce=k_a__nonce + self.originator_key_info=originator_key_info + self.recipient_key_info=recipient_key_info + self.algorithm=algorithm - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.uri = uri - self.transforms = transforms or [] +def agreement_method_type_from_string(xml_string): + return saml2.create_class_from_xml_string(AgreementMethodType, xml_string) -def cipher_reference_from_string(xml_string): - """ Create CipherReference instance from an XML string """ - return create_class_from_xml_string(CipherReference, xml_string) - -# --------------------------------------------------------------------------- -# CipherData -# --------------------------------------------------------------------------- - -class CipherData(EncBase): - """The enc:CipherData element""" - - c_tag = 'CipherData' - c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_children['{%s}CipherValue' % NAMESPACE] = ( - 'cipher_value', [CipherValue]) - c_children['{%s}CipherReference' % NAMESPACE] = ( - 'cipher_reference', [CipherReference]) - c_child_order = ['cipher_value', 'cipher_reference'] - - def __init__(self, algorithm=None, cipher_value=None, - cipher_reference=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for CipherData - - :param cipher_value: CipherValue attribute - :param cipher_reference: CipherReference attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.cipher_value = cipher_value - self.cipher_reference = cipher_reference - -def cipher_data_from_string(xml_string): - """ Create CipherData instance from an XML string """ - return create_class_from_xml_string(CipherData, xml_string) - -# --------------------------------------------------------------------------- -# EncryptionProperty -# --------------------------------------------------------------------------- - -class EncryptionProperty(EncBase): - - c_tag = 'EncryptionProperty' - c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_attributes['Target'] = 'target' - c_attributes['Id'] = 'identifier' - - def __init__(self, target=None, identifier=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for EncryptedKey - - :param target: Target attribute - :param identifier: Id attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.target = target - self.identifier = identifier or [] - -def encryption_property_from_string(xml_string): - """ Create EncryptionProperty instance from an XML string """ - return create_class_from_xml_string(EncryptionProperty, xml_string) - -# --------------------------------------------------------------------------- -# EncryptionProperties -# --------------------------------------------------------------------------- - -class EncryptionProperties(EncBase): - - c_tag = 'EncryptionProperties' - c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_attributes['Id'] = 'identifier' - c_children['{%s}EncryptionProperty' % NAMESPACE] = ( - 'encryption_property', [EncryptionProperty]) - - def __init__(self, identifier=None, encryption_property=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for EncryptedKey - - :param identifier: Id attribute - :param encryption_property: EncryptionProperty attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.identifier = identifier - self.encryption_property = encryption_property or [] - -def encryption_properties_from_string(xml_string): - """ Create EncryptionProperties instance from an XML string """ - return create_class_from_xml_string(EncryptionProperties, xml_string) - -# --------------------------------------------------------------------------- -# EncryptedType -# --------------------------------------------------------------------------- - -class EncryptedType(EncBase): - """The enc:EncryptedType element""" - - c_tag = 'EncryptedType' - c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_attributes['Id'] = 'identifier' - c_attributes['Type'] = 'typ' - c_attributes['MimeType'] = 'mime_type' - c_attributes['Encoding'] = 'encoding' - c_children['{%s}EncryptionMethod' % NAMESPACE] = ( - 'encryption_method', [EncryptionMethod]) - c_children['{%s}KeyInfo' % ds.NAMESPACE] = ( - 'key_info', [ds.KeyInfo]) - c_children['{%s}CipherData' % NAMESPACE] = ( - 'cipher_data', [CipherData]) - c_children['{%s}EncryptionProperties' % NAMESPACE] = ( - 'encryption_properties', [EncryptionProperties]) - c_child_order = ['encryption_method', 'key_info', - 'cipher_data','encryption_properties'] - - def __init__(self, identifier=None, typ=None, mime_type=None, - encoding=None, encryption_method=None, key_info=None, - cipher_data=None, encryption_properties=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for EncryptedType - - :param identifier: Id attribute - :param typ: Type attribute - :param mime_type: MimeType attribute - :param encoding: Encoding attribute - :param encryption_method: EncryptionMethod attribute - :param key_info: KeyInfo attribute - :param cipher_data: CipherData attribute - :param encryption_properties: EncryptionProperties attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.identifier = identifier - self.typ = typ - self.mime_type = mime_type - self.encoding = encoding - self.encryption_method = encryption_method - self.key_info = key_info - self.cipher_data = cipher_data - self.encryption_properties = encryption_properties - -def encrypted_type_from_string(xml_string): - """ Create EncryptedType instance from an XML string """ - return create_class_from_xml_string(EncryptedType, xml_string) - -# --------------------------------------------------------------------------- -# EncryptedData -# --------------------------------------------------------------------------- - -class EncryptedData(EncryptedType): - """The enc:EncryptedData element""" - - c_tag = 'EncryptedData' - c_namespace = NAMESPACE - c_children = EncryptedType.c_children.copy() - c_attributes = EncryptedType.c_attributes.copy() - -def encrypted_data_from_string(xml_string): - """ Create EncryptedData instance from an XML string """ - return create_class_from_xml_string(EncryptedData, xml_string) - -# --------------------------------------------------------------------------- -# ReferenceType -# --------------------------------------------------------------------------- - -class ReferenceType(EncBase): +class ReferenceType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:ReferenceType element """ c_tag = 'ReferenceType' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_attributes['URI'] = 'uri' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['URI'] = ('uri', 'anyURI', True) - def __init__(self, uri=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for ReferenceType + def __init__(self, + uri=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.uri=uri - :param uri: URI attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.uri = uri - def reference_type_from_string(xml_string): - """ Create ReferenceType instance from an XML string """ - return create_class_from_xml_string(ReferenceType, xml_string) + return saml2.create_class_from_xml_string(ReferenceType, xml_string) -# --------------------------------------------------------------------------- -# DataReference -# --------------------------------------------------------------------------- +class EncryptionPropertyType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:EncryptionPropertyType element """ + + c_tag = 'EncryptionPropertyType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_attributes['Target'] = ('target', 'anyURI', False) + c_attributes['Id'] = ('id', 'ID', False) + + def __init__(self, + target=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.target=target + self.id=id + +def encryption_property_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptionPropertyType, xml_string) + +class KeySize(KeySizeType): + """The http://www.w3.org/2001/04/xmlenc#:KeySize element """ + + c_tag = 'KeySize' + c_namespace = NAMESPACE + c_children = KeySizeType.c_children.copy() + c_attributes = KeySizeType.c_attributes.copy() + c_child_order = KeySizeType.c_child_order[:] + +def key_size_from_string(xml_string): + return saml2.create_class_from_xml_string(KeySize, xml_string) + +class OAEPparams(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:OAEPparams element """ + + c_tag = 'OAEPparams' + c_namespace = NAMESPACE + c_value_type = 'base64Binary' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def oae_pparams_from_string(xml_string): + return saml2.create_class_from_xml_string(OAEPparams, xml_string) + +class EncryptionMethodType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:EncryptionMethodType element """ + + c_tag = 'EncryptionMethodType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}KeySize'] = ('key_size', KeySize) + c_children['{http://www.w3.org/2001/04/xmlenc#}OAEPparams'] = ('oae_pparams', OAEPparams) + c_attributes['Algorithm'] = ('algorithm', 'anyURI', True) + c_child_order.extend(['key_size', 'oae_pparams']) + + def __init__(self, + key_size=None, + oae_pparams=None, + algorithm=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.key_size=key_size + self.oae_pparams=oae_pparams + self.algorithm=algorithm + +def encryption_method_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptionMethodType, xml_string) + +class Transforms(TransformsType): + """The http://www.w3.org/2001/04/xmlenc#:Transforms element """ + + c_tag = 'Transforms' + c_namespace = NAMESPACE + c_children = TransformsType.c_children.copy() + c_attributes = TransformsType.c_attributes.copy() + c_child_order = TransformsType.c_child_order[:] + +def transforms_from_string(xml_string): + return saml2.create_class_from_xml_string(Transforms, xml_string) + +class CipherReferenceType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:CipherReferenceType element """ + + c_tag = 'CipherReferenceType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}Transforms'] = ('transforms', Transforms) + c_attributes['URI'] = ('uri', 'anyURI', True) + c_child_order.extend(['transforms']) + + def __init__(self, + transforms=None, + uri=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.transforms=transforms + self.uri=uri + +def cipher_reference_type_from_string(xml_string): + return saml2.create_class_from_xml_string(CipherReferenceType, xml_string) + +class AgreementMethod(AgreementMethodType): + """The http://www.w3.org/2001/04/xmlenc#:AgreementMethod element """ + + c_tag = 'AgreementMethod' + c_namespace = NAMESPACE + c_children = AgreementMethodType.c_children.copy() + c_attributes = AgreementMethodType.c_attributes.copy() + c_child_order = AgreementMethodType.c_child_order[:] + +def agreement_method_from_string(xml_string): + return saml2.create_class_from_xml_string(AgreementMethod, xml_string) class DataReference(ReferenceType): + """The http://www.w3.org/2001/04/xmlenc#:DataReference element """ c_tag = 'DataReference' c_namespace = NAMESPACE c_children = ReferenceType.c_children.copy() c_attributes = ReferenceType.c_attributes.copy() + c_child_order = ReferenceType.c_child_order[:] def data_reference_from_string(xml_string): - """ Create DataReference instance from an XML string """ - return create_class_from_xml_string(DataReference, xml_string) - -# --------------------------------------------------------------------------- -# KeyReference -# --------------------------------------------------------------------------- + return saml2.create_class_from_xml_string(DataReference, xml_string) class KeyReference(ReferenceType): + """The http://www.w3.org/2001/04/xmlenc#:KeyReference element """ c_tag = 'KeyReference' c_namespace = NAMESPACE c_children = ReferenceType.c_children.copy() c_attributes = ReferenceType.c_attributes.copy() + c_child_order = ReferenceType.c_child_order[:] def key_reference_from_string(xml_string): - """ Create KeyReference instance from an XML string """ - return create_class_from_xml_string(KeyReference, xml_string) + return saml2.create_class_from_xml_string(KeyReference, xml_string) -# --------------------------------------------------------------------------- -# ReferenceList -# --------------------------------------------------------------------------- - -class ReferenceList(EncBase): +class ReferenceList(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:ReferenceList element """ c_tag = 'ReferenceList' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() - c_children['{%s}DataReference' % NAMESPACE] = ( - 'data_reference', [DataReference]) - c_children['{%s}KeyReference' % NAMESPACE] = ( - 'key_reference', [KeyReference]) + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}DataReference'] = ('data_reference', [DataReference]) + c_children['{http://www.w3.org/2001/04/xmlenc#}KeyReference'] = ('key_reference', [KeyReference]) + c_child_order.extend(['data_reference', 'key_reference']) - def __init__(self, data_reference=None, key_reference=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for EncryptedKey + def __init__(self, + data_reference=None, + key_reference=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.data_reference=data_reference or [] + self.key_reference=key_reference or [] - :param data_reference: DataReference attribute - :param key_reference: KeyReference attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ - - EncBase.__init__(self, text, extension_elements, extension_attributes) - self.data_reference = data_reference or [] - self.key_reference = key_reference or [] - def reference_list_from_string(xml_string): - """ Create ReferenceList instance from an XML string """ - return create_class_from_xml_string(ReferenceList, xml_string) + return saml2.create_class_from_xml_string(ReferenceList, xml_string) -# --------------------------------------------------------------------------- -# CarriedKeyName -# --------------------------------------------------------------------------- +class EncryptionProperty(EncryptionPropertyType): + """The http://www.w3.org/2001/04/xmlenc#:EncryptionProperty element """ -class CarriedKeyName(EncBase): - - c_tag = 'CarriedKeyName' + c_tag = 'EncryptionProperty' c_namespace = NAMESPACE - c_children = EncBase.c_children.copy() - c_attributes = EncBase.c_attributes.copy() + c_children = EncryptionPropertyType.c_children.copy() + c_attributes = EncryptionPropertyType.c_attributes.copy() + c_child_order = EncryptionPropertyType.c_child_order[:] -def carried_key_name_from_string(xml_string): - """ Create CarriedKeyName instance from an XML string """ - return create_class_from_xml_string(CarriedKeyName, xml_string) +def encryption_property_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptionProperty, xml_string) -# --------------------------------------------------------------------------- -# EncryptedKey -# --------------------------------------------------------------------------- +class CipherReference(CipherReferenceType): + """The http://www.w3.org/2001/04/xmlenc#:CipherReference element """ -class EncryptedKey(EncryptedType): - """The enc:EncryptedKey element""" + c_tag = 'CipherReference' + c_namespace = NAMESPACE + c_children = CipherReferenceType.c_children.copy() + c_attributes = CipherReferenceType.c_attributes.copy() + c_child_order = CipherReferenceType.c_child_order[:] - c_tag = 'EncryptedKey' +def cipher_reference_from_string(xml_string): + return saml2.create_class_from_xml_string(CipherReference, xml_string) + +class EncryptionPropertiesType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:EncryptionPropertiesType element """ + + c_tag = 'EncryptionPropertiesType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptionProperty'] = ('encryption_property', [EncryptionProperty]) + c_attributes['Id'] = ('id', 'ID', False) + c_child_order.extend(['encryption_property']) + + def __init__(self, + encryption_property=None, + id=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.encryption_property=encryption_property or [] + self.id=id + +def encryption_properties_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptionPropertiesType, xml_string) + +class CipherValue(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:CipherValue element """ + + c_tag = 'CipherValue' + c_namespace = NAMESPACE + c_value_type = 'CipherValue' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def cipher_value_from_string(xml_string): + return saml2.create_class_from_xml_string(CipherValue, xml_string) + +class CipherDataType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:CipherDataType element """ + + c_tag = 'CipherDataType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}CipherValue'] = ('cipher_value', CipherValue) + c_children['{http://www.w3.org/2001/04/xmlenc#}CipherReference'] = ('cipher_reference', CipherReference) + c_child_order.extend(['cipher_value', 'cipher_reference']) + + def __init__(self, + cipher_value=None, + cipher_reference=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.cipher_value=cipher_value + self.cipher_reference=cipher_reference + +def cipher_data_type_from_string(xml_string): + return saml2.create_class_from_xml_string(CipherDataType, xml_string) + +class EncryptionProperties(EncryptionPropertiesType): + """The http://www.w3.org/2001/04/xmlenc#:EncryptionProperties element """ + + c_tag = 'EncryptionProperties' + c_namespace = NAMESPACE + c_children = EncryptionPropertiesType.c_children.copy() + c_attributes = EncryptionPropertiesType.c_attributes.copy() + c_child_order = EncryptionPropertiesType.c_child_order[:] + +def encryption_properties_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptionProperties, xml_string) + +class CipherData(CipherDataType): + """The http://www.w3.org/2001/04/xmlenc#:CipherData element """ + + c_tag = 'CipherData' + c_namespace = NAMESPACE + c_children = CipherDataType.c_children.copy() + c_attributes = CipherDataType.c_attributes.copy() + c_child_order = CipherDataType.c_child_order[:] + +def cipher_data_from_string(xml_string): + return saml2.create_class_from_xml_string(CipherData, xml_string) + +class EncryptionMethod(EncryptionMethodType): + """The http://www.w3.org/2001/04/xmlenc#:EncryptionMethod element """ + + c_tag = 'EncryptionMethod' + c_namespace = NAMESPACE + c_children = EncryptionMethodType.c_children.copy() + c_attributes = EncryptionMethodType.c_attributes.copy() + c_child_order = EncryptionMethodType.c_child_order[:] + +def encryption_method_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptionMethod, xml_string) + +class EncryptedType(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:EncryptedType element """ + + c_tag = 'EncryptedType' + c_namespace = NAMESPACE + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptionMethod'] = ('encryption_method', EncryptionMethod) + c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', ds.KeyInfo) + c_children['{http://www.w3.org/2001/04/xmlenc#}CipherData'] = ('cipher_data', CipherData) + c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptionProperties'] = ('encryption_properties', EncryptionProperties) + c_attributes['Id'] = ('id', 'ID', False) + c_attributes['Type'] = ('type', 'anyURI', False) + c_attributes['MimeType'] = ('mime_type', 'string', False) + c_attributes['Encoding'] = ('encoding', 'anyURI', False) + c_child_order.extend(['encryption_method', 'key_info', 'cipher_data', 'encryption_properties']) + + def __init__(self, + encryption_method=None, + key_info=None, + cipher_data=None, + encryption_properties=None, + id=None, + type=None, + mime_type=None, + encoding=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + SamlBase.__init__(self, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.encryption_method=encryption_method + self.key_info=key_info + self.cipher_data=cipher_data + self.encryption_properties=encryption_properties + self.id=id + self.type=type + self.mime_type=mime_type + self.encoding=encoding + +def encrypted_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptedType, xml_string) + +class EncryptedDataType(EncryptedType): + """The http://www.w3.org/2001/04/xmlenc#:EncryptedDataType element """ + + c_tag = 'EncryptedDataType' c_namespace = NAMESPACE c_children = EncryptedType.c_children.copy() c_attributes = EncryptedType.c_attributes.copy() - c_attributes['Recipient'] = 'recipient' - c_children['{%s}ReferenceList' % NAMESPACE] = ( - 'reference_list', [ReferenceList]) - c_children['{%s}CarriedKeyName' % NAMESPACE] = ( - 'carried_key_name', [CarriedKeyName]) + c_child_order = EncryptedType.c_child_order[:] - def __init__(self, recipient=None, reference_list=None, - carried_key_name=None,identifier=None, typ=None, - mime_type=None, encoding=None, encryption_method=None, - key_info=None, cipher_data=None, encryption_properties=None, - text=None, extension_elements=None, extension_attributes=None): - """Constructor for EncryptedType +def encrypted_data_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptedDataType, xml_string) - :param recipient: Id attribute - :param reference_list: Type attribute - :param carried_key_name: MimeType attribute - :param identifier: Id attribute - :param typ: Type attribute - :param mime_type: MimeType attribute - :param encoding: Encoding attribute - :param encryption_method: EncryptionMethod attribute - :param key_info: KeyInfo attribute - :param cipher_data: CipherData attribute - :param encryption_properties: EncryptionProperties attribute - :param text: The text data in the this element - :param extension_elements: A list of ExtensionElement instances - :param extension_attributes: A dictionary of attribute value string - pairs - """ +class CarriedKeyName(SamlBase): + """The http://www.w3.org/2001/04/xmlenc#:CarriedKeyName element """ - EncryptedType.__init__(self, identifier, typ, mime_type, - encoding, encryption_method, key_info, - cipher_data, encryption_properties, - text, extension_elements, extension_attributes) - self.recipient = recipient - self.reference_list = reference_list or [] - self.carried_key_name = carried_key_name or [] + c_tag = 'CarriedKeyName' + c_namespace = NAMESPACE + c_value_type = 'string' + c_children = SamlBase.c_children.copy() + c_attributes = SamlBase.c_attributes.copy() + c_child_order = SamlBase.c_child_order[:] + +def carried_key_name_from_string(xml_string): + return saml2.create_class_from_xml_string(CarriedKeyName, xml_string) + +class EncryptedKeyType(EncryptedType): + """The http://www.w3.org/2001/04/xmlenc#:EncryptedKeyType element """ + + c_tag = 'EncryptedKeyType' + c_namespace = NAMESPACE + c_children = EncryptedType.c_children.copy() + c_attributes = EncryptedType.c_attributes.copy() + c_child_order = EncryptedType.c_child_order[:] + c_children['{http://www.w3.org/2001/04/xmlenc#}ReferenceList'] = ('reference_list', ReferenceList) + c_children['{http://www.w3.org/2001/04/xmlenc#}CarriedKeyName'] = ('carried_key_name', CarriedKeyName) + c_attributes['Recipient'] = ('recipient', 'string', False) + c_child_order.extend(['reference_list', 'carried_key_name']) + + def __init__(self, + reference_list=None, + carried_key_name=None, + recipient=None, + encryption_method=None, + key_info=None, + cipher_data=None, + encryption_properties=None, + id=None, + type=None, + mime_type=None, + encoding=None, + text=None, + extension_elements=None, + extension_attributes=None, + ): + EncryptedType.__init__(self, + encryption_method=encryption_method, + key_info=key_info, + cipher_data=cipher_data, + encryption_properties=encryption_properties, + id=id, + type=type, + mime_type=mime_type, + encoding=encoding, + text=text, + extension_elements=extension_elements, + extension_attributes=extension_attributes, + ) + self.reference_list=reference_list + self.carried_key_name=carried_key_name + self.recipient=recipient + +def encrypted_key_type_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptedKeyType, xml_string) + +class EncryptedData(EncryptedDataType): + """The http://www.w3.org/2001/04/xmlenc#:EncryptedData element """ + + c_tag = 'EncryptedData' + c_namespace = NAMESPACE + c_children = EncryptedDataType.c_children.copy() + c_attributes = EncryptedDataType.c_attributes.copy() + c_child_order = EncryptedDataType.c_child_order[:] + +def encrypted_data_from_string(xml_string): + return saml2.create_class_from_xml_string(EncryptedData, xml_string) + +class EncryptedKey(EncryptedKeyType): + """The http://www.w3.org/2001/04/xmlenc#:EncryptedKey element """ + + c_tag = 'EncryptedKey' + c_namespace = NAMESPACE + c_children = EncryptedKeyType.c_children.copy() + c_attributes = EncryptedKeyType.c_attributes.copy() + c_child_order = EncryptedKeyType.c_child_order[:] def encrypted_key_from_string(xml_string): - """ Create EncryptedKey instance from an XML string """ - return create_class_from_xml_string(EncryptedKey, xml_string) + return saml2.create_class_from_xml_string(EncryptedKey, xml_string) -ds.KeyInfo.c_children['{%s}EncryptedKey' % NAMESPACE] = ( - 'encrypted_key', [EncryptedKey]) +ELEMENT_FROM_STRING = { + EncryptedType.c_tag: encrypted_type_from_string, + EncryptionMethodType.c_tag: encryption_method_type_from_string, + KeySizeType.c_tag: key_size_type_from_string, + CipherData.c_tag: cipher_data_from_string, + CipherDataType.c_tag: cipher_data_type_from_string, + CipherReference.c_tag: cipher_reference_from_string, + CipherReferenceType.c_tag: cipher_reference_type_from_string, + TransformsType.c_tag: transforms_type_from_string, + EncryptedData.c_tag: encrypted_data_from_string, + EncryptedDataType.c_tag: encrypted_data_type_from_string, + EncryptedKey.c_tag: encrypted_key_from_string, + EncryptedKeyType.c_tag: encrypted_key_type_from_string, + AgreementMethod.c_tag: agreement_method_from_string, + AgreementMethodType.c_tag: agreement_method_type_from_string, + ReferenceList.c_tag: reference_list_from_string, + ReferenceType.c_tag: reference_type_from_string, + EncryptionProperties.c_tag: encryption_properties_from_string, + EncryptionPropertiesType.c_tag: encryption_properties_type_from_string, + EncryptionProperty.c_tag: encryption_property_from_string, + EncryptionPropertyType.c_tag: encryption_property_type_from_string, +} -# ========================================= +ELEMENT_BY_TAG = { + 'EncryptedType': EncryptedType, + 'EncryptionMethodType': EncryptionMethodType, + 'KeySizeType': KeySizeType, + 'CipherData': CipherData, + 'CipherDataType': CipherDataType, + 'CipherReference': CipherReference, + 'CipherReferenceType': CipherReferenceType, + 'TransformsType': TransformsType, + 'EncryptedData': EncryptedData, + 'EncryptedDataType': EncryptedDataType, + 'EncryptedKey': EncryptedKey, + 'EncryptedKeyType': EncryptedKeyType, + 'AgreementMethod': AgreementMethod, + 'AgreementMethodType': AgreementMethodType, + 'ReferenceList': ReferenceList, + 'ReferenceType': ReferenceType, + 'EncryptionProperties': EncryptionProperties, + 'EncryptionPropertiesType': EncryptionPropertiesType, + 'EncryptionProperty': EncryptionProperty, + 'EncryptionPropertyType': EncryptionPropertyType, +} + +def factory(tag, **kwargs): + return ELEMENT_BY_TAG[tag](**kwargs) -ELEMENT_TO_STRING = { - KeySize: key_size_from_string, - OAEPparams: oaep_params_from_string, - EncryptionMethod: encryption_method_from_string, - CipherValue: cipher_value_from_string, - Transforms: transforms_from_string, - CipherReference: cipher_reference_from_string, - CipherData: cipher_data_from_string, - EncryptionProperty: encryption_property_from_string, - EncryptionProperties: encryption_properties_from_string, - EncryptedType: encrypted_type_from_string, - EncryptedData: encrypted_data_from_string, - ReferenceType: reference_type_from_string, - DataReference: data_reference_from_string, - KeyReference: key_reference_from_string, - ReferenceList: reference_list_from_string, - CarriedKeyName: carried_key_name_from_string, - EncryptedKey: encrypted_key_from_string, -} \ No newline at end of file diff --git a/tests/ds_data.py b/tests/ds_data.py index b30b8d2..b827223 100644 --- a/tests/ds_data.py +++ b/tests/ds_data.py @@ -54,7 +54,7 @@ TEST_PGP_DATA = """ TEST_X509_ISSUER_SERIAL = """ issuer name - 1 + 1 """ diff --git a/tests/idp.config b/tests/idp.config index 45cf253..6c0b878 100644 --- a/tests/idp.config +++ b/tests/idp.config @@ -3,15 +3,18 @@ "service": { "idp": { "name" : "Rolands IdP", - "url": "http://localhost:8088/sso", + "endpoints" : { + "single_sign_on_service" : ["http://localhost:8088/sso"], + }, "policy": { "default": { "lifetime": {"minutes":15}, "attribute_restrictions": None, # means all I have - "name_form": "urn:oasis:names:tc:SAML:2.0:attrname-format:uri" + "name_form": "urn:oasis:names:tc:SAML:2.0:attrname-format:uri", }, "urn:mace:example.com:saml:roland:sp": { "lifetime": {"minutes": 5}, + "nameid_format": "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", # "attribute_restrictions":{ # "givenName": None, # "surName": None, diff --git a/tests/md_data.py b/tests/md_data.py index ba92bae..22bb3b0 100644 --- a/tests/md_data.py +++ b/tests/md_data.py @@ -19,7 +19,7 @@ __author__ = 'tmatsuo@example.com (Takashi MATSUO)' TEST_ENDPOINT = """ - TEST_INDEXED_ENDPOINT = """ - TEST_ORGANIZATION_NAME = """ - SIOS Technology, Inc. + xml:lang="se"> + Catalogix """ -TEST_ORGANIZATION_DISPLAY_NAME = """ - - SIOS - +TEST_ORGANIZATION_DISPLAY_NAME = """ + +Catalogix + """ TEST_ORGANIZATION_URL = """ + xml:lang="no"> http://www.example.com/ """ @@ -141,15 +139,14 @@ TEST_ORGANIZATION = """ hogehoge - SIOS Technology, Inc. + xml:lang="se"> + Catalogix AB - - SIOS + + Catalogix AS + xml:lang="en"> http://www.example.com/ @@ -447,7 +444,7 @@ TEST_ROLE_DESCRIPTOR = """ TEST_SSO_DESCRIPTOR = """ - urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress - + """ @@ -888,15 +885,15 @@ TEST_REQUESTED_ATTRIBUTE = """ TEST_SERVICE_NAME = """ - SIOS mail + xml:lang="en"> + Catalogix Whois """ TEST_SERVICE_DESCRIPTION = """ - SIOS mail service + xml:lang="en"> +Catalogix Whois Service """ @@ -1283,7 +1280,7 @@ TEST_ENTITY_DESCRIPTOR = """ TEST_ENTITIES_DESCRIPTOR = """ diff --git a/tests/restrictive_idp.config b/tests/restrictive_idp.config index 7966b88..37c9a2d 100644 --- a/tests/restrictive_idp.config +++ b/tests/restrictive_idp.config @@ -3,7 +3,9 @@ "service": { "idp": { "name" : "Rolands restrictied IdP", - "url": "http://localhost:8089/sso", + "endpoints" : { + "single_sign_on_service" : ["http://localhost:8089/sso"], + }, "assertions": { "default": { "lifetime": {"minutes":15}, @@ -22,7 +24,9 @@ }, "aa": { "name" : "Rolands restrictied AA", - "url": "http://localhost:8089/sso", + "endpoints" : { + "attribute_service" : ["http://localhost:8089/aa"], + }, "assertions": { "default": { "lifetime": {"minutes":15}, diff --git a/tests/samlp_data.py b/tests/samlp_data.py index 4ea06aa..7c76628 100644 --- a/tests/samlp_data.py +++ b/tests/samlp_data.py @@ -96,7 +96,7 @@ TEST_AUTHN_REQUEST = """ AssertionConsumerServiceIndex="1" AssertionConsumerServiceURL="http://www.example.com/acs" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" - AssertionConsumingServiceIndex="2" + AttributeConsumingServiceIndex="2" ProviderName="provider name" xmlns="urn:oasis:names:tc:SAML:2.0:protocol"> diff --git a/tests/server.config b/tests/server.config index 6fdd5cc..293eba5 100644 --- a/tests/server.config +++ b/tests/server.config @@ -3,11 +3,14 @@ "service": { "sp":{ "name" : "urn:mace:example.com:saml:roland:sp", - "url": "http://lingon.catalogix.se:8087/", + "description": "My own SP", + "endpoints":{ + "assertion_consumer_service": ["http://lingon.catalogix.se:8087/"], + }, "required_attributes": ["surName", "givenName", "mail"], "optional_attributes": ["title"], "idp":{ - "entity_id": ["urn:mace:example.com:saml:roland:idp"], + "urn:mace:example.com:saml:roland:idp":None, }, } }, @@ -27,4 +30,17 @@ "subject_data": "subject_data.db", "accept_time_diff": 60, "attribute_map_dir" : "attributemaps", + "organization": { + "name": ("AB Exempel", "se"), + "display_name": ("AB Exempel", "se"), + "url": "http://www.example.org", + }, + "contact_person": [{ + "given_name": "Roland", + "sur_name": "Hedberg", + "telephone_number": "+46 70 100 0000", + "email_address": ["tech@eample.com", "tech@example.org"], + "contact_type": "technical" + }, + ] } \ No newline at end of file diff --git a/tests/test_00_saml2.py b/tests/test_00_saml2.py deleted file mode 100644 index 94b0553..0000000 --- a/tests/test_00_saml2.py +++ /dev/null @@ -1,541 +0,0 @@ -#!/usr/bin/env python - -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 -import saml2 -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:[""" - - roland@example.com - -""", """ -_1632879f09d08ea5ede2dc667cbed7e429ebc4335c -""", """ -test -"""], - Issuer:""" - - http://www.example.com/test - -""", - SubjectLocality: """ - -""", - SubjectConfirmationData: -""" -""", - SubjectConfirmation: - """ -test@example.com - -""" -} - -#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( - """bar""") - 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( - """bar""") - 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( - """ - bar""") - 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( - """ - - xyztre""") - 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( - """ - bar""") - - ce = saml2.extension_element_from_string( - """ - rev""") - - 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( - """ - bar""") - - ce = saml2.extension_element_from_string( - """ - rev""") - - 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 = """ - - roland@example.com - -""" - -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 = """ - -test@example.com - - - -Excellent - -""" - -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_int(): - kl = make_vals(1024,md.KeySize, part=True) - assert isinstance(kl, md.KeySize) - assert kl.text == "1024" - -def test_exception_make_vals_int_not_part(): - raises(TypeError, "make_vals(1024,md.KeySize)") - raises(TypeError, "make_vals(1024,md.KeySize,md.EncryptionMethod())") - raises(AttributeError, "make_vals(1024,md.KeySize,prop='key_size')") - -def test_make_vals_list_of_ints(): - em = md.EncryptionMethod() - make_vals([1024,2048], md.KeySize, em, "key_size") - assert len(em.key_size) == 2 - -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_exception_make_vals_value_error(): - raises(ValueError, "make_vals((1024,'xyz'), md.KeySize, part=True)") - - -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( - """ - - - - http://federationX.org - - - - https://federationX.org/?ID=a87s76a5765da76576a57as - - -""") - - 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" diff --git a/tests/test_01_saml.py b/tests/test_01_saml.py deleted file mode 100644 index 05b9552..0000000 --- a/tests/test_01_saml.py +++ /dev/null @@ -1,989 +0,0 @@ -#!/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 -from saml2 import saml -import saml2_data, ds_data -import xmldsig as ds - -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.URN_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.URN_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 = """ - -By-Tor -""" - -BASIC_INT_AV = """ - -23 -""" - -BASIC_NOT_INT_AV = """ - -foo -""" - -BASIC_BOOLEAN_TRUE_AV = """ - -true -""" - -BASIC_BOOLEAN_FALSE_AV = """ - -false -""" - -BASIC_BASE64_AV = """ - -VU5JTkVUVA== -""" - -X500_AV = """ - -Steven - -""" - -UUID_AV = """ - -1 -""" - -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): - 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].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.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.Condition) - - 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.Condition) - - -class TestProxyRestriction: - - def setup_class(self): - self.proxy_restriction = saml.ProxyRestriction() - - def testAccessors(self): - """Test for ProxyRestriction accessors""" - - assert isinstance(self.proxy_restriction, saml.Condition) - 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.append(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[0], - 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 diff --git a/tests/test_02_md.py b/tests/test_02_md.py deleted file mode 100644 index deb49a5..0000000 --- a/tests/test_02_md.py +++ /dev/null @@ -1,1166 +0,0 @@ -#!/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.md""" - -__author__ = 'roland.hedberg@umu.se (Roland Hedberg)' - -import unittest -try: - from xml.etree import ElementTree -except ImportError: - from elementtree import ElementTree -import saml2 -from saml2 import saml, samlp, md, extension_element_to_element -from saml2 import element_to_extension_element -import md_data, ds_data -import xmldsig as ds - -class TestEndpoint: - - def setup_class(self): - self.endpoint = md.Endpoint() - - def testAccessors(self): - """Test for Endpoint accessors""" - self.endpoint.binding = saml2.BINDING_HTTP_POST - self.endpoint.location = "http://www.example.com/endpoint" - self.endpoint.response_location = "http://www.example.com/response" - print self.endpoint.__class__.c_attributes.items() - new_endpoint = md.endpoint_from_string(self.endpoint.to_string()) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - def testUsingTestData(self): - """Test for endpoint_from_string() using test data.""" - new_endpoint = md.endpoint_from_string(md_data.TEST_ENDPOINT) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - -class TestIndexedEndpoint: - - def setup_class(self): - self.i_e = md.IndexedEndpoint() - - def testAccessors(self): - """Test for IndexedEndpoint accessors""" - self.i_e.binding = saml2.BINDING_HTTP_POST - self.i_e.location = "http://www.example.com/endpoint" - self.i_e.response_location = "http://www.example.com/response" - self.i_e.index = "1" - self.i_e.is_default = "false" - new_i_e = md.indexed_endpoint_from_string(self.i_e.to_string()) - assert new_i_e.binding == saml2.BINDING_HTTP_POST - assert new_i_e.location == "http://www.example.com/endpoint" - assert new_i_e.response_location == "http://www.example.com/response" - assert new_i_e.index == "1" - assert new_i_e.is_default == "false" - - def testUsingTestData(self): - """Test for indexed_endpoint_from_string() using test data.""" - new_i_e = md.indexed_endpoint_from_string(md_data.TEST_INDEXED_ENDPOINT) - assert new_i_e.binding == saml2.BINDING_HTTP_POST - assert new_i_e.location == "http://www.example.com/endpoint" - assert new_i_e.response_location == "http://www.example.com/response" - assert new_i_e.index == "1" - assert new_i_e.is_default == "false" - - -class TestExtensions: - - def setup_class(self): - self.extensions = md.Extensions() - - def testAccessors(self): - """Test for Extensions accessors""" - self.extensions.extension_elements.append( - saml2.extension_element_from_string( - """ - fuga - """)) - new_extensions = md.extensions_from_string(self.extensions.to_string()) - assert new_extensions.extension_elements[0].tag == "hoge" - assert new_extensions.extension_elements[0].text.strip() == "fuga" - - -class TestOrganizationName: - - def setup_class(self): - self.organization_name = md.OrganizationName() - - def testAccessors(self): - """Test for OrganizationName accessors""" - self.organization_name.lang = "en" - self.organization_name.text = "SIOS Technology, Inc." - new_organization_name = md.organization_name_from_string( - self.organization_name.to_string()) - assert new_organization_name.lang == "en" - assert new_organization_name.text.strip() == "SIOS Technology, Inc." - - def testUsingTestData(self): - """Test for organization_name_from_string() using test data.""" - new_organization_name = md.organization_name_from_string( - md_data.TEST_ORGANIZATION_NAME) - assert new_organization_name.lang == "en" - assert new_organization_name.text.strip() == "SIOS Technology, Inc." - - -class TestOrganizationDisplayName: - - def setup_class(self): - self.od_name = md.OrganizationDisplayName() - - def testAccessors(self): - """Test for OrganizationDisplayName accessors""" - self.od_name.lang = "en" - self.od_name.text = "SIOS" - new_od_name = md.organization_display_name_from_string( - self.od_name.to_string()) - assert new_od_name.lang == "en" - assert new_od_name.text.strip() == "SIOS" - - def testUsingTestData(self): - """Test for organization_display_name_from_string() using test data.""" - new_od_name = md.organization_display_name_from_string( - md_data.TEST_ORGANIZATION_DISPLAY_NAME) - assert new_od_name.lang == "en" - assert new_od_name.text.strip() == "SIOS" - - -class TestOrganizationURL: - - def setup_class(self): - self.organization_url = md.OrganizationURL() - - def testAccessors(self): - """Test for OrganizationURL accessors""" - self.organization_url.lang = "ja" - self.organization_url.text = "http://www.example.com/" - new_organization_url = md.organization_url_from_string( - self.organization_url.to_string()) - assert new_organization_url.lang == "ja" - assert new_organization_url.text.strip() == "http://www.example.com/" - - def testUsingTestData(self): - """Test for organization_url_from_string() using test data.""" - new_organization_url = md.organization_url_from_string( - md_data.TEST_ORGANIZATION_URL) - assert new_organization_url.lang == "ja" - assert new_organization_url.text.strip() == "http://www.example.com/" - - -class TestOrganization: - - def setup_class(self): - self.organization = md.Organization() - - def testAccessors(self): - """Test for Organization accessors""" - self.organization.extensions = md.Extensions() - self.organization.organization_name.append( - md.organization_name_from_string(md_data.TEST_ORGANIZATION_NAME)) - self.organization.organization_display_name.append( - md.organization_display_name_from_string( - md_data.TEST_ORGANIZATION_DISPLAY_NAME)) - self.organization.organization_url.append( - md.organization_url_from_string(md_data.TEST_ORGANIZATION_URL)) - new_organization = md.organization_from_string(self.organization.to_string()) - assert isinstance(new_organization.extensions, md.Extensions) - assert isinstance(new_organization.organization_name[0], - md.OrganizationName) - assert isinstance(new_organization.organization_display_name[0], - md.OrganizationDisplayName) - assert isinstance(new_organization.organization_url[0], - md.OrganizationURL) - assert new_organization.organization_name[0].text.strip() == "SIOS Technology, Inc." - assert new_organization.organization_name[0].lang == "en" - assert new_organization.organization_display_name[0].text.strip() == "SIOS" - assert new_organization.organization_display_name[0].lang == "en" - assert new_organization.organization_url[0].text.strip() == "http://www.example.com/" - assert new_organization.organization_url[0].lang == "ja" - - - def testUsingTestData(self): - """Test for organization_from_string() using test data.""" - new_organization = md.organization_from_string( - md_data.TEST_ORGANIZATION) - assert isinstance(new_organization.extensions, md.Extensions) - assert isinstance(new_organization.organization_name[0], - md.OrganizationName) - assert isinstance(new_organization.organization_display_name[0], - md.OrganizationDisplayName) - assert isinstance(new_organization.organization_url[0], - md.OrganizationURL) - assert new_organization.organization_name[0].text.strip() == "SIOS Technology, Inc." - assert new_organization.organization_name[0].lang == "en" - assert new_organization.organization_display_name[0].text.strip() == "SIOS" - assert new_organization.organization_display_name[0].lang == "en" - assert new_organization.organization_url[0].text.strip() == "http://www.example.com/" - assert new_organization.organization_url[0].lang == "ja" - - -class TestContactPerson: - - def setup_class(self): - self.contact_person = md.ContactPerson() - - def testAccessors(self): - """Test for ContactPerson accessors""" - self.contact_person.contact_type = "technical" - self.contact_person.extensions = md.Extensions() - self.contact_person.company = md.Company(text="SIOS Technology, Inc.") - self.contact_person.given_name = md.GivenName(text="Takashi") - self.contact_person.sur_name = md.SurName(text="Matsuo") - self.contact_person.email_address.append( - md.EmailAddress(text="tmatsuo@example.com")) - self.contact_person.email_address.append( - md.EmailAddress(text="tmatsuo@shehas.net")) - self.contact_person.telephone_number.append( - md.TelephoneNumber(text="00-0000-0000")) - new_contact_person = md.contact_person_from_string( - self.contact_person.to_string()) - assert new_contact_person.contact_type == "technical" - assert isinstance(new_contact_person.extensions, md.Extensions) - assert new_contact_person.company.text.strip() == "SIOS Technology, Inc." - assert new_contact_person.given_name.text.strip() == "Takashi" - assert new_contact_person.sur_name.text.strip() == "Matsuo" - assert new_contact_person.email_address[0].text.strip() == "tmatsuo@example.com" - assert new_contact_person.email_address[1].text.strip() == "tmatsuo@shehas.net" - assert new_contact_person.telephone_number[0].text.strip() == "00-0000-0000" - - def testUsingTestData(self): - """Test for contact_person_from_string() using test data.""" - new_contact_person = md.contact_person_from_string( - md_data.TEST_CONTACT_PERSON) - assert new_contact_person.contact_type == "technical" - assert isinstance(new_contact_person.extensions, md.Extensions) - assert new_contact_person.company.text.strip() == "SIOS Technology, Inc." - assert new_contact_person.given_name.text.strip() == "Takashi" - assert new_contact_person.sur_name.text.strip() == "Matsuo" - assert new_contact_person.email_address[0].text.strip() == "tmatsuo@example.com" - assert new_contact_person.email_address[1].text.strip() == "tmatsuo@shehas.net" - assert new_contact_person.telephone_number[0].text.strip() == "00-0000-0000" - -class TestAdditionalMetadataLocation: - - def setup_class(self): - self.additional_metadata_location = md.AdditionalMetadataLocation() - - def testAccessors(self): - """Test for AdditionalMetadataLocation accessors""" - self.additional_metadata_location.namespace = ( - "http://www.example.com/namespace") - self.additional_metadata_location.text = ( - "http://www.example.com/AdditionalMetadataLocation") - new_additional_metadata_location = md.additional_metadata_location_from_string( - self.additional_metadata_location.to_string()) - assert new_additional_metadata_location.namespace == "http://www.example.com/namespace" - assert new_additional_metadata_location.text.strip() == "http://www.example.com/AdditionalMetadataLocation" - - def testUsingTestData(self): - """Test for additional_metadata_location_from_string() using test data.""" - new_additional_metadata_location = md.additional_metadata_location_from_string( - md_data.TEST_ADDITIONAL_METADATA_LOCATION) - assert new_additional_metadata_location.namespace == "http://www.example.com/namespace" - assert new_additional_metadata_location.text.strip() == "http://www.example.com/AdditionalMetadataLocation" - -class TestKeySize: - - def setup_class(self): - self.key_size = md.KeySize() - - def testAccessors(self): - """Test for KeySize accessors""" - self.key_size.text = "128" - new_key_size = md.key_size_from_string(self.key_size.to_string()) - assert new_key_size.text.strip() == "128" - - def testUsingTestData(self): - """Test for key_size_from_string() using test data.""" - new_key_size = md.key_size_from_string(md_data.TEST_KEY_SIZE) - assert new_key_size.text.strip() == "128" - - -class TestOAEPparams: - - def setup_class(self): - self.oaep_params = md.OAEPparams() - - def testAccessors(self): - """Test for OAEPparams accessors""" - self.oaep_params.text = "9lWu3Q==" - new_oaep_params = md.oae_pparams_from_string(self.oaep_params.to_string()) - assert new_oaep_params.text.strip() == "9lWu3Q==" - - def testUsingTestData(self): - """Test for oae_pparams_from_string() using test data.""" - new_oaep_params = md.oae_pparams_from_string(md_data.TEST_OAEP_PARAMS) - assert new_oaep_params.text.strip() == "9lWu3Q==" - - -class TestEncryptionMethod: - - def setup_class(self): - self.encryption_method = md.EncryptionMethod() - - def testAccessors(self): - """Test for EncryptionMethod accessors""" - self.encryption_method.algorithm = ( - "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p") - self.encryption_method.oaep_params = md.OAEPparams(text="9lWu3Q==") - self.encryption_method.digest_method = ds.DigestMethod( - algorithm="http://www.w3.org/2000/09/xmldsig#sha1") - new_encryption_method = md.encryption_method_from_string( - self.encryption_method.to_string()) - assert new_encryption_method.algorithm == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" - assert new_encryption_method.oaep_params.text.strip() == "9lWu3Q==" - assert new_encryption_method.digest_method.algorithm == "http://www.w3.org/2000/09/xmldsig#sha1" - - def testUsingTestData(self): - """Test for encryption_method_from_string() using test data.""" - new_encryption_method = md.encryption_method_from_string( - md_data.TEST_ENCRYPTION_METHOD) - assert new_encryption_method.algorithm == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" - assert new_encryption_method.oaep_params.text.strip() == "9lWu3Q==" - assert new_encryption_method.digest_method.algorithm == "http://www.w3.org/2000/09/xmldsig#sha1" - - -class TestKeyDescriptor: - - def setup_class(self): - self.key_descriptor = md.KeyDescriptor() - - def testAccessors(self): - """Test for KeyDescriptor accessors""" - - self.key_descriptor.use = "signing" - self.key_descriptor.key_info = ds.key_info_from_string( - ds_data.TEST_KEY_INFO) - self.key_descriptor.encryption_method.append(md.encryption_method_from_string( - md_data.TEST_ENCRYPTION_METHOD)) - new_key_descriptor = md.key_descriptor_from_string( - self.key_descriptor.to_string()) - assert new_key_descriptor.use == "signing" - assert isinstance(new_key_descriptor.key_info, ds.KeyInfo) - assert isinstance(new_key_descriptor.encryption_method[0], - md.EncryptionMethod) - - def testUsingTestData(self): - """Test for key_descriptor_from_string() using test data.""" - new_key_descriptor = md.key_descriptor_from_string( - md_data.TEST_KEY_DESCRIPTOR) - assert new_key_descriptor.use == "signing" - assert isinstance(new_key_descriptor.key_info, ds.KeyInfo) - assert isinstance(new_key_descriptor.encryption_method[0], - md.EncryptionMethod) - - -class TestRoleDescriptor: - def setup_class(self): - self.role_descriptor = md.RoleDescriptor() - - def testAccessors(self): - """Test for RoleDescriptor accessors""" - self.role_descriptor.id = "ID" - self.role_descriptor.valid_until = "2008-09-14T01:05:02Z" - self.role_descriptor.cache_duration = "10:00:00:00" - self.role_descriptor.protocol_support_enumeration = samlp.NAMESPACE - self.role_descriptor.error_url = "http://www.example.com/errorURL" - self.role_descriptor.signature = ds.get_empty_signature() - self.role_descriptor.extensions = md.Extensions() - self.role_descriptor.key_descriptor.append(md.key_descriptor_from_string( - md_data.TEST_KEY_DESCRIPTOR)) - self.role_descriptor.organization = md.Organization() - self.role_descriptor.contact_person.append(md.ContactPerson()) - - new_role_descriptor = md.role_descriptor_from_string( - self.role_descriptor.to_string()) - assert new_role_descriptor.id == "ID" - assert new_role_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_role_descriptor.cache_duration == "10:00:00:00" - assert new_role_descriptor.protocol_support_enumeration == samlp.NAMESPACE - assert new_role_descriptor.error_url == "http://www.example.com/errorURL" - assert isinstance(new_role_descriptor.signature, ds.Signature) - assert isinstance(new_role_descriptor.extensions, md.Extensions) - assert isinstance(new_role_descriptor.key_descriptor[0], - md.KeyDescriptor) - assert isinstance(new_role_descriptor.organization, md.Organization) - assert isinstance(new_role_descriptor.contact_person[0], - md.ContactPerson) - - def testUsingTestData(self): - """Test for role_descriptor_from_string() using test data.""" - new_role_descriptor = md.role_descriptor_from_string( - md_data.TEST_ROLE_DESCRIPTOR) - assert new_role_descriptor.id == "ID" - assert new_role_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_role_descriptor.cache_duration == "10:00:00:00" - assert new_role_descriptor.protocol_support_enumeration == samlp.NAMESPACE - assert new_role_descriptor.error_url == "http://www.example.com/errorURL" - assert isinstance(new_role_descriptor.signature, ds.Signature) - assert isinstance(new_role_descriptor.extensions, md.Extensions) - assert isinstance(new_role_descriptor.key_descriptor[0], - md.KeyDescriptor) - assert isinstance(new_role_descriptor.organization, md.Organization) - assert isinstance(new_role_descriptor.contact_person[0], - md.ContactPerson) - -class TestSSODescriptor: - def setup_class(self): - self.sso_descriptor = md.SSODescriptor() - - def testAccessors(self): - """Test for SSODescriptor accessors""" - self.sso_descriptor.id = "ID" - self.sso_descriptor.valid_until = "2008-09-14T01:05:02Z" - self.sso_descriptor.cache_duration = "10:00:00:00" - self.sso_descriptor.protocol_support_enumeration = samlp.NAMESPACE - self.sso_descriptor.error_url = "http://www.example.com/errorURL" - self.sso_descriptor.signature = ds.get_empty_signature() - self.sso_descriptor.extensions = md.Extensions() - self.sso_descriptor.key_descriptor.append(md.key_descriptor_from_string( - md_data.TEST_KEY_DESCRIPTOR)) - self.sso_descriptor.organization = md.Organization() - self.sso_descriptor.contact_person.append(md.ContactPerson()) - self.sso_descriptor.artifact_resolution_service.append( - md.ArtifactResolutionService()) - self.sso_descriptor.single_logout_service.append( - md.SingleLogoutService()) - self.sso_descriptor.manage_name_id_service.append( - md.ManageNameIDService()) - self.sso_descriptor.name_id_format.append( - md.NameIDFormat()) - - new_sso_descriptor = md.sso_descriptor_from_string( - self.sso_descriptor.to_string()) - assert new_sso_descriptor.id == "ID" - assert new_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_sso_descriptor.cache_duration == "10:00:00:00" - assert new_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE - assert new_sso_descriptor.error_url == "http://www.example.com/errorURL" - assert isinstance(new_sso_descriptor.signature, ds.Signature) - assert isinstance(new_sso_descriptor.extensions, md.Extensions) - assert isinstance(new_sso_descriptor.key_descriptor[0], - md.KeyDescriptor) - assert isinstance(new_sso_descriptor.organization, md.Organization) - assert isinstance(new_sso_descriptor.contact_person[0], - md.ContactPerson) - assert isinstance(new_sso_descriptor.artifact_resolution_service[0], - md.ArtifactResolutionService) - assert isinstance(new_sso_descriptor.single_logout_service[0], - md.SingleLogoutService) - assert isinstance(new_sso_descriptor.manage_name_id_service[0], - md.ManageNameIDService) - assert isinstance(new_sso_descriptor.name_id_format[0], - md.NameIDFormat) - - def testUsingTestData(self): - """Test for sso_descriptor_from_string() using test data.""" - new_sso_descriptor = md.sso_descriptor_from_string( - md_data.TEST_SSO_DESCRIPTOR) - assert new_sso_descriptor.id == "ID" - assert new_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_sso_descriptor.cache_duration == "10:00:00:00" - assert new_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE - assert new_sso_descriptor.error_url == "http://www.example.com/errorURL" - assert isinstance(new_sso_descriptor.signature, ds.Signature) - assert isinstance(new_sso_descriptor.extensions, md.Extensions) - assert isinstance(new_sso_descriptor.key_descriptor[0], - md.KeyDescriptor) - assert isinstance(new_sso_descriptor.organization, md.Organization) - assert isinstance(new_sso_descriptor.contact_person[0], - md.ContactPerson) - assert isinstance(new_sso_descriptor.artifact_resolution_service[0], - md.ArtifactResolutionService) - assert isinstance(new_sso_descriptor.single_logout_service[0], - md.SingleLogoutService) - assert isinstance(new_sso_descriptor.manage_name_id_service[0], - md.ManageNameIDService) - assert isinstance(new_sso_descriptor.name_id_format[0], - md.NameIDFormat) - - -class TestArtifactResolutionService: - - def setup_class(self): - self.i_e = md.ArtifactResolutionService() - - def testAccessors(self): - """Test for ArtifactResolutionService accessors""" - self.i_e.binding = saml2.BINDING_HTTP_POST - self.i_e.location = "http://www.example.com/endpoint" - self.i_e.response_location = "http://www.example.com/response" - self.i_e.index = "1" - self.i_e.is_default = "false" - new_i_e = md.artifact_resolution_service_from_string(self.i_e.to_string()) - assert new_i_e.binding == saml2.BINDING_HTTP_POST - assert new_i_e.location == "http://www.example.com/endpoint" - assert new_i_e.response_location == "http://www.example.com/response" - assert new_i_e.index == "1" - assert new_i_e.is_default == "false" - - def testUsingTestData(self): - """Test for artifact_resolution_service_from_string() using test data.""" - new_i_e = md.artifact_resolution_service_from_string( - md_data.TEST_ARTIFACT_RESOLUTION_SERVICE) - assert new_i_e.binding == saml2.BINDING_HTTP_POST - assert new_i_e.location == "http://www.example.com/endpoint" - assert new_i_e.response_location == "http://www.example.com/response" - assert new_i_e.index == "1" - assert new_i_e.is_default == "false" - - -class TestSingleLogout: - - def setup_class(self): - self.endpoint = md.SingleLogoutService() - - def testAccessors(self): - """Test for SingleLogoutService accessors""" - self.endpoint.binding = saml2.BINDING_HTTP_POST - self.endpoint.location = "http://www.example.com/endpoint" - self.endpoint.response_location = "http://www.example.com/response" - new_endpoint = md.single_logout_service_from_string(self.endpoint.to_string()) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - def testUsingTestData(self): - """Test for single_logout_service_from_string() using test data.""" - new_endpoint = md.single_logout_service_from_string( - md_data.TEST_SINGLE_LOGOUT_SERVICE) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - -class TestManageNameIDService: - - def setup_class(self): - self.endpoint = md.ManageNameIDService() - - def testAccessors(self): - """Test for ManageNameIDService accessors""" - self.endpoint.binding = saml2.BINDING_HTTP_POST - self.endpoint.location = "http://www.example.com/endpoint" - self.endpoint.response_location = "http://www.example.com/response" - new_endpoint = md.manage_name_id_service_from_string(self.endpoint.to_string()) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - def testUsingTestData(self): - """Test for manage_name_id_service_from_string() using test data.""" - new_endpoint = md.manage_name_id_service_from_string( - md_data.TEST_MANAGE_NAMEID_SERVICE) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - -class TestNameIDFormat: - - def setup_class(self): - self.name_id_format = md.NameIDFormat() - - def testAccessors(self): - """Test for NameIDFormat accessors""" - self.name_id_format.text = saml.NAMEID_FORMAT_EMAILADDRESS - new_name_id_format = md.name_id_format_from_string( - self.name_id_format.to_string()) - assert new_name_id_format.text.strip() == saml.NAMEID_FORMAT_EMAILADDRESS - - def testUsingTestData(self): - """Test for name_id_format_from_string() using test data.""" - new_name_id_format = md.name_id_format_from_string( - md_data.TEST_NAME_ID_FORMAT) - assert new_name_id_format.text.strip() == saml.NAMEID_FORMAT_EMAILADDRESS - - -class TestSingleSignOnService: - - def setup_class(self): - self.endpoint = md.SingleSignOnService() - - def testAccessors(self): - """Test for SingelSignOnService accessors""" - self.endpoint.binding = saml2.BINDING_HTTP_POST - self.endpoint.location = "http://www.example.com/endpoint" - self.endpoint.response_location = "http://www.example.com/response" - new_endpoint = md.single_sign_on_service_from_string(self.endpoint.to_string()) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - def testUsingTestData(self): - """Test for SingelSignOn_service_from_string() using test data.""" - new_endpoint = md.single_sign_on_service_from_string( - md_data.TEST_SINGLE_SIGN_ON_SERVICE) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - -class TestNameIDMappingService: - - def setup_class(self): - self.endpoint = md.NameIDMappingService() - - def testAccessors(self): - """Test for NameIDMappingService accessors""" - self.endpoint.binding = saml2.BINDING_HTTP_POST - self.endpoint.location = "http://www.example.com/endpoint" - self.endpoint.response_location = "http://www.example.com/response" - new_endpoint = md.name_id_mapping_service_from_string(self.endpoint.to_string()) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - def testUsingTestData(self): - """Test for name_id_mapping_service_from_string() using test data.""" - new_endpoint = md.name_id_mapping_service_from_string( - md_data.TEST_NAME_ID_MAPPING_SERVICE) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - -class TestAssertionIDRequestService: - - def setup_class(self): - self.endpoint = md.AssertionIDRequestService() - - def testAccessors(self): - """Test for AssertionIDRequestService accessors""" - self.endpoint.binding = saml2.BINDING_HTTP_POST - self.endpoint.location = "http://www.example.com/endpoint" - self.endpoint.response_location = "http://www.example.com/response" - new_endpoint = md.assertion_id_request_service_from_string( - self.endpoint.to_string()) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - - def testUsingTestData(self): - """Test for assertion_id_request_service_from_string() using test data.""" - new_endpoint = md.assertion_id_request_service_from_string( - md_data.TEST_ASSERTION_ID_REQUEST_SERVICE) - assert new_endpoint.binding == saml2.BINDING_HTTP_POST - assert new_endpoint.location == "http://www.example.com/endpoint" - assert new_endpoint.response_location == "http://www.example.com/response" - -class TestAttributeProfile: - - def setup_class(self): - self.attribute_profile = md.AttributeProfile() - - def testAccessors(self): - """Test for AttributeProfile accessors""" - self.attribute_profile.text = saml.PROFILE_ATTRIBUTE_BASIC - new_attribute_profile = md.attribute_profile_from_string( - self.attribute_profile.to_string()) - assert new_attribute_profile.text.strip() == saml.PROFILE_ATTRIBUTE_BASIC - - def testUsingTestData(self): - """Test for name_id_format_from_string() using test data.""" - new_attribute_profile = md.attribute_profile_from_string( - md_data.TEST_ATTRIBUTE_PROFILE) - assert new_attribute_profile.text.strip() == saml.PROFILE_ATTRIBUTE_BASIC - - -class TestIDPSSODescriptor: - def setup_class(self): - self.idp_sso_descriptor = md.IDPSSODescriptor() - - def testAccessors(self): - """Test for IDPSSODescriptor accessors""" - self.idp_sso_descriptor.id = "ID" - self.idp_sso_descriptor.valid_until = "2008-09-14T01:05:02Z" - self.idp_sso_descriptor.cache_duration = "10:00:00:00" - self.idp_sso_descriptor.protocol_support_enumeration = \ - samlp.NAMESPACE - self.idp_sso_descriptor.error_url = "http://www.example.com/errorURL" - self.idp_sso_descriptor.signature = ds.get_empty_signature() - self.idp_sso_descriptor.extensions = md.Extensions() - self.idp_sso_descriptor.key_descriptor.append(md.key_descriptor_from_string( - md_data.TEST_KEY_DESCRIPTOR)) - self.idp_sso_descriptor.organization = md.Organization() - self.idp_sso_descriptor.contact_person.append(md.ContactPerson()) - self.idp_sso_descriptor.artifact_resolution_service.append( - md.ArtifactResolutionService()) - self.idp_sso_descriptor.single_logout_service.append( - md.SingleLogoutService()) - self.idp_sso_descriptor.manage_name_id_service.append( - md.ManageNameIDService()) - self.idp_sso_descriptor.name_id_format.append( - md.NameIDFormat()) - self.idp_sso_descriptor.want_authn_requests_signed = 'true' - self.idp_sso_descriptor.single_sign_on_service.append( - md.SingleSignOnService()) - self.idp_sso_descriptor.name_id_mapping_service.append( - md.NameIDMappingService()) - self.idp_sso_descriptor.assertion_id_request_service.append( - md.AssertionIDRequestService()) - self.idp_sso_descriptor.attribute_profile.append( - md.AttributeProfile()) - self.idp_sso_descriptor.attribute.append(saml.Attribute()) - - new_idp_sso_descriptor = md.idpsso_descriptor_from_string( - self.idp_sso_descriptor.to_string()) - assert new_idp_sso_descriptor.id == "ID" - assert new_idp_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_idp_sso_descriptor.cache_duration == "10:00:00:00" - assert new_idp_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE - assert new_idp_sso_descriptor.error_url == "http://www.example.com/errorURL" - assert isinstance(new_idp_sso_descriptor.signature, ds.Signature) - assert isinstance(new_idp_sso_descriptor.extensions, md.Extensions) - assert isinstance(new_idp_sso_descriptor.key_descriptor[0], - md.KeyDescriptor) - assert isinstance(new_idp_sso_descriptor.organization, - md.Organization) - assert isinstance(new_idp_sso_descriptor.contact_person[0], - md.ContactPerson) - assert isinstance( - new_idp_sso_descriptor.artifact_resolution_service[0], - md.ArtifactResolutionService) - assert isinstance(new_idp_sso_descriptor.single_logout_service[0], - md.SingleLogoutService) - assert isinstance(new_idp_sso_descriptor.manage_name_id_service[0], - md.ManageNameIDService) - assert isinstance(new_idp_sso_descriptor.name_id_format[0], - md.NameIDFormat) - assert new_idp_sso_descriptor.want_authn_requests_signed == "true" - assert isinstance(new_idp_sso_descriptor.single_sign_on_service[0], - md.SingleSignOnService) - assert isinstance(new_idp_sso_descriptor.name_id_mapping_service[0], - md.NameIDMappingService) - assert isinstance( - new_idp_sso_descriptor.assertion_id_request_service[0], - md.AssertionIDRequestService) - assert isinstance(new_idp_sso_descriptor.attribute_profile[0], - md.AttributeProfile) - assert isinstance(new_idp_sso_descriptor.attribute[0], - saml.Attribute) - - def testUsingTestData(self): - """Test for idpsso_descriptor_from_string() using test data.""" - new_idp_sso_descriptor = md.idpsso_descriptor_from_string( - md_data.TEST_IDP_SSO_DESCRIPTOR) - assert new_idp_sso_descriptor.id == "ID" - assert new_idp_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_idp_sso_descriptor.cache_duration == "10:00:00:00" - assert new_idp_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE - assert new_idp_sso_descriptor.error_url == "http://www.example.com/errorURL" - assert isinstance(new_idp_sso_descriptor.signature, ds.Signature) - assert isinstance(new_idp_sso_descriptor.extensions, md.Extensions) - assert isinstance(new_idp_sso_descriptor.key_descriptor[0], - md.KeyDescriptor) - assert isinstance(new_idp_sso_descriptor.organization, - md.Organization) - assert isinstance(new_idp_sso_descriptor.contact_person[0], - md.ContactPerson) - assert isinstance( - new_idp_sso_descriptor.artifact_resolution_service[0], - md.ArtifactResolutionService) - assert isinstance(new_idp_sso_descriptor.single_logout_service[0], - md.SingleLogoutService) - assert isinstance(new_idp_sso_descriptor.manage_name_id_service[0], - md.ManageNameIDService) - assert isinstance(new_idp_sso_descriptor.name_id_format[0], - md.NameIDFormat) - assert new_idp_sso_descriptor.want_authn_requests_signed == "true" - assert isinstance(new_idp_sso_descriptor.single_sign_on_service[0], - md.SingleSignOnService) - assert isinstance(new_idp_sso_descriptor.name_id_mapping_service[0], - md.NameIDMappingService) - assert isinstance( - new_idp_sso_descriptor.assertion_id_request_service[0], - md.AssertionIDRequestService) - assert isinstance(new_idp_sso_descriptor.attribute_profile[0], - md.AttributeProfile) - assert isinstance(new_idp_sso_descriptor.attribute[0], - saml.Attribute) - - -class TestAssertionConsumerService: - - def setup_class(self): - self.i_e = md.AssertionConsumerService() - - def testAccessors(self): - """Test for AssertionConsumerService accessors""" - self.i_e.binding = saml2.BINDING_HTTP_POST - self.i_e.location = "http://www.example.com/endpoint" - self.i_e.response_location = "http://www.example.com/response" - self.i_e.index = "1" - self.i_e.is_default = "false" - new_i_e = md.assertion_consumer_service_from_string(self.i_e.to_string()) - assert new_i_e.binding == saml2.BINDING_HTTP_POST - assert new_i_e.location == "http://www.example.com/endpoint" - assert new_i_e.response_location == "http://www.example.com/response" - assert new_i_e.index == "1" - assert new_i_e.is_default == "false" - - def testUsingTestData(self): - """Test for assertion_consumer_service_from_string() using test data.""" - new_i_e = md.assertion_consumer_service_from_string( - md_data.TEST_ASSERTION_CONSUMER_SERVICE) - assert new_i_e.binding == saml2.BINDING_HTTP_POST - assert new_i_e.location == "http://www.example.com/endpoint" - assert new_i_e.response_location == "http://www.example.com/response" - assert new_i_e.index == "1" - assert new_i_e.is_default == "false" - - -class TestRequestedAttribute: - - def setup_class(self): - self.requested_attribute = md.RequestedAttribute() - - def testAccessors(self): - """Test for RequestedAttribute accessors""" - assert isinstance(self.requested_attribute, saml.Attribute) - assert isinstance(self.requested_attribute, md.RequestedAttribute) - assert self.requested_attribute.is_required is None - self.requested_attribute.is_required = "true" - new_requested_attribute = md.requested_attribute_from_string( - self.requested_attribute.to_string()) - assert new_requested_attribute.is_required == "true" - assert isinstance(new_requested_attribute, saml.Attribute) - assert isinstance(new_requested_attribute, md.RequestedAttribute) - - def testUsingTestData(self): - """Test for requested_attribute_from_string() using test data.""" - new_requested_attribute = md.requested_attribute_from_string( - md_data.TEST_REQUESTED_ATTRIBUTE) - assert new_requested_attribute.is_required == "true" - assert isinstance(new_requested_attribute, saml.Attribute) - assert isinstance(new_requested_attribute, md.RequestedAttribute) - - -class TestServiceName: - - def setup_class(self): - self.service_name = md.ServiceName() - - def testAccessors(self): - """Test for ServiceName accessors""" - self.service_name.lang = "en" - self.service_name.text = "SIOS mail" - new_service_name = md.service_name_from_string(self.service_name.to_string()) - assert new_service_name.lang == "en" - assert new_service_name.text.strip() == "SIOS mail" - - def testUsingTestData(self): - """Test for organization_name_from_string() using test data.""" - new_service_name = md.service_name_from_string(md_data.TEST_SERVICE_NAME) - assert new_service_name.lang == "en" - assert new_service_name.text.strip() == "SIOS mail" - - -class TestServiceDescription: - - def setup_class(self): - self.service_description = md.ServiceDescription() - - def testAccessors(self): - """Test for ServiceDescription accessors""" - self.service_description.lang = "en" - self.service_description.text = "SIOS mail service" - new_service_description = md.service_description_from_string( - self.service_description.to_string()) - assert new_service_description.lang == "en" - assert new_service_description.text.strip() == "SIOS mail service" - - def testUsingTestData(self): - """Test for organization_name_from_string() using test data.""" - new_service_description = md.service_description_from_string( - md_data.TEST_SERVICE_DESCRIPTION) - assert new_service_description.lang == "en" - assert new_service_description.text.strip() == "SIOS mail service" - - -class TestAttributeConsumingService: - - def setup_class(self): - self.attribute_consuming_service = md.AttributeConsumingService() - - def testAccessors(self): - """Test for AttributeConsumingService accessors""" - self.attribute_consuming_service.service_name.append(md.ServiceName()) - self.attribute_consuming_service.service_description.append( - md.ServiceDescription()) - self.attribute_consuming_service.requested_attribute.append( - md.RequestedAttribute()) - self.attribute_consuming_service.index = "1" - self.attribute_consuming_service.is_default = "true" - - new_attribute_consuming_service = md.attribute_consuming_service_from_string( - self.attribute_consuming_service.to_string()) - assert new_attribute_consuming_service.index == "1" - assert new_attribute_consuming_service.is_default == "true" - assert isinstance(new_attribute_consuming_service.service_name[0], - md.ServiceName) - assert isinstance( - new_attribute_consuming_service.service_description[0], - md.ServiceDescription) - assert isinstance( - new_attribute_consuming_service.requested_attribute[0], - md.RequestedAttribute) - - def testUsingTestData(self): - """Test for attribute_consuming_service_from_string() using test data.""" - new_attribute_consuming_service = md.attribute_consuming_service_from_string( - md_data.TEST_ATTRIBUTE_CONSUMING_SERVICE) - assert new_attribute_consuming_service.index == "1" - assert new_attribute_consuming_service.is_default == "true" - assert isinstance(new_attribute_consuming_service.service_name[0], - md.ServiceName) - assert isinstance( - new_attribute_consuming_service.service_description[0], - md.ServiceDescription) - assert isinstance( - new_attribute_consuming_service.requested_attribute[0], - md.RequestedAttribute) - - -class TestSPSSODescriptor: - def setup_class(self): - self.sp_sso_descriptor = md.SPSSODescriptor() - - def testAccessors(self): - """Test for SPSSODescriptor accessors""" - self.sp_sso_descriptor.id = "ID" - self.sp_sso_descriptor.valid_until = "2008-09-14T01:05:02Z" - self.sp_sso_descriptor.cache_duration = "10:00:00:00" - self.sp_sso_descriptor.protocol_support_enumeration = \ - samlp.NAMESPACE - self.sp_sso_descriptor.error_url = "http://www.example.com/errorURL" - self.sp_sso_descriptor.signature = ds.get_empty_signature() - self.sp_sso_descriptor.extensions = md.Extensions() - self.sp_sso_descriptor.key_descriptor.append(md.key_descriptor_from_string( - md_data.TEST_KEY_DESCRIPTOR)) - self.sp_sso_descriptor.organization = md.Organization() - self.sp_sso_descriptor.contact_person.append(md.ContactPerson()) - self.sp_sso_descriptor.artifact_resolution_service.append( - md.ArtifactResolutionService()) - self.sp_sso_descriptor.single_logout_service.append( - md.SingleLogoutService()) - self.sp_sso_descriptor.manage_name_id_service.append( - md.ManageNameIDService()) - self.sp_sso_descriptor.name_id_format.append( - md.NameIDFormat()) - self.sp_sso_descriptor.authn_requests_signed = "true" - self.sp_sso_descriptor.want_assertions_signed = "true" - self.sp_sso_descriptor.assertion_consumer_service.append( - md.AssertionConsumerService()) - self.sp_sso_descriptor.attribute_consuming_service.append( - md.AttributeConsumingService()) - - print self.sp_sso_descriptor - new_sp_sso_descriptor = md.spsso_descriptor_from_string( - self.sp_sso_descriptor.to_string()) - print new_sp_sso_descriptor - assert new_sp_sso_descriptor.id == "ID" - assert new_sp_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_sp_sso_descriptor.cache_duration == "10:00:00:00" - assert new_sp_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE - assert new_sp_sso_descriptor.error_url == "http://www.example.com/errorURL" - assert isinstance(new_sp_sso_descriptor.signature, ds.Signature) - assert isinstance(new_sp_sso_descriptor.extensions, md.Extensions) - assert isinstance(new_sp_sso_descriptor.key_descriptor[0], - md.KeyDescriptor) - assert isinstance(new_sp_sso_descriptor.organization, - md.Organization) - assert isinstance(new_sp_sso_descriptor.contact_person[0], - md.ContactPerson) - assert isinstance( - new_sp_sso_descriptor.artifact_resolution_service[0], - md.ArtifactResolutionService) - assert isinstance(new_sp_sso_descriptor.single_logout_service[0], - md.SingleLogoutService) - assert isinstance(new_sp_sso_descriptor.manage_name_id_service[0], - md.ManageNameIDService) - assert isinstance(new_sp_sso_descriptor.name_id_format[0], - md.NameIDFormat) - assert new_sp_sso_descriptor.authn_requests_signed == "true" - assert new_sp_sso_descriptor.want_assertions_signed == "true" - assert isinstance( - new_sp_sso_descriptor.assertion_consumer_service[0], - md.AssertionConsumerService) - assert isinstance( - new_sp_sso_descriptor.attribute_consuming_service[0], - md.AttributeConsumingService) - - def testUsingTestData(self): - """Test for spsso_descriptor_from_string() using test data.""" - new_sp_sso_descriptor = md.spsso_descriptor_from_string( - md_data.TEST_SP_SSO_DESCRIPTOR) - assert new_sp_sso_descriptor.id == "ID" - assert new_sp_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_sp_sso_descriptor.cache_duration == "10:00:00:00" - assert new_sp_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE - assert new_sp_sso_descriptor.error_url == "http://www.example.com/errorURL" - assert isinstance(new_sp_sso_descriptor.signature, ds.Signature) - assert isinstance(new_sp_sso_descriptor.extensions, md.Extensions) - print new_sp_sso_descriptor.extensions.__dict__ - assert len(new_sp_sso_descriptor.extensions.extension_elements) == 2 - for eelem in new_sp_sso_descriptor.extensions.extension_elements: - print "EE",eelem.__dict__ - dp = extension_element_to_element(eelem, md.ELEMENT_FROM_STRING, - md.IDPDISC) - print "DP",dp.c_tag, dp.c_namespace,dp.__dict__ - assert isinstance(dp, md.DiscoveryResponse) - assert isinstance(new_sp_sso_descriptor.key_descriptor[0], - md.KeyDescriptor) - assert isinstance(new_sp_sso_descriptor.organization, - md.Organization) - assert isinstance(new_sp_sso_descriptor.contact_person[0], - md.ContactPerson) - assert isinstance( - new_sp_sso_descriptor.artifact_resolution_service[0], - md.ArtifactResolutionService) - assert isinstance(new_sp_sso_descriptor.single_logout_service[0], - md.SingleLogoutService) - assert isinstance(new_sp_sso_descriptor.manage_name_id_service[0], - md.ManageNameIDService) - assert isinstance(new_sp_sso_descriptor.name_id_format[0], - md.NameIDFormat) - assert new_sp_sso_descriptor.authn_requests_signed == "true" - assert new_sp_sso_descriptor.want_assertions_signed == "true" - assert isinstance( - new_sp_sso_descriptor.assertion_consumer_service[0], - md.AssertionConsumerService) - assert isinstance( - new_sp_sso_descriptor.attribute_consuming_service[0], - md.AttributeConsumingService) - - -class TestEntityDescriptor: - def setup_class(self): - self.entity_descriptor = md.EntityDescriptor() - - def testAccessors(self): - """Test for RoleDescriptor accessors""" - self.entity_descriptor.id = "ID" - self.entity_descriptor.entity_id = "entityID" - self.entity_descriptor.valid_until = "2008-09-14T01:05:02Z" - self.entity_descriptor.cache_duration = "10:00:00:00" - - self.entity_descriptor.signature = ds.get_empty_signature() - self.entity_descriptor.extensions = md.Extensions() - self.entity_descriptor.role_descriptor.append(md.RoleDescriptor()) - self.entity_descriptor.idp_sso_descriptor.append(md.IDPSSODescriptor()) - self.entity_descriptor.sp_sso_descriptor.append(md.SPSSODescriptor()) - self.entity_descriptor.organization = md.Organization() - self.entity_descriptor.contact_person.append(md.ContactPerson()) - self.entity_descriptor.additional_metadata_location.append( - md.AdditionalMetadataLocation()) - - new_entity_descriptor = md.entity_descriptor_from_string( - self.entity_descriptor.to_string()) - assert new_entity_descriptor.id == "ID" - assert new_entity_descriptor.entity_id == "entityID" - assert new_entity_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_entity_descriptor.cache_duration == "10:00:00:00" - assert isinstance(new_entity_descriptor.signature, ds.Signature) - assert isinstance(new_entity_descriptor.extensions, md.Extensions) - assert isinstance(new_entity_descriptor.role_descriptor[0], - md.RoleDescriptor) - assert isinstance(new_entity_descriptor.idp_sso_descriptor[0], - md.IDPSSODescriptor) - assert isinstance(new_entity_descriptor.sp_sso_descriptor[0], - md.SPSSODescriptor) - assert isinstance(new_entity_descriptor.organization, - md.Organization) - assert isinstance(new_entity_descriptor.contact_person[0], - md.ContactPerson) - assert isinstance( - new_entity_descriptor.additional_metadata_location[0], - md.AdditionalMetadataLocation) - - def testUsingTestData(self): - """Test for entity_descriptor_from_string() using test data.""" - new_entity_descriptor = md.entity_descriptor_from_string( - md_data.TEST_ENTITY_DESCRIPTOR) - assert new_entity_descriptor.id == "ID" - assert new_entity_descriptor.entity_id == "entityID" - assert new_entity_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_entity_descriptor.cache_duration == "10:00:00:00" - assert isinstance(new_entity_descriptor.signature, ds.Signature) - assert isinstance(new_entity_descriptor.extensions, md.Extensions) - assert isinstance(new_entity_descriptor.role_descriptor[0], - md.RoleDescriptor) - assert isinstance(new_entity_descriptor.idp_sso_descriptor[0], - md.IDPSSODescriptor) - assert isinstance(new_entity_descriptor.sp_sso_descriptor[0], - md.SPSSODescriptor) - assert isinstance(new_entity_descriptor.organization, - md.Organization) - assert isinstance(new_entity_descriptor.contact_person[0], - md.ContactPerson) - assert isinstance(new_entity_descriptor.additional_metadata_location[0], - md.AdditionalMetadataLocation) - - -class TestEntitiesDescriptor: - def setup_class(self): - self.entities_descriptor = md.EntitiesDescriptor() - - def testAccessors(self): - """Test for EntitiesDescriptor accessors""" - self.entities_descriptor.id = "ID" - self.entities_descriptor.name = "name" - self.entities_descriptor.valid_until = "2008-09-14T01:05:02Z" - self.entities_descriptor.cache_duration = "10:00:00:00" - - self.entities_descriptor.signature = ds.get_empty_signature() - self.entities_descriptor.extensions = md.Extensions() - self.entities_descriptor.entity_descriptor.append(md.EntityDescriptor()) - self.entities_descriptor.entities_descriptor.append( - md.EntitiesDescriptor()) - - new_entities_descriptor = md.entities_descriptor_from_string( - self.entities_descriptor.to_string()) - assert new_entities_descriptor.id == "ID" - assert new_entities_descriptor.name == "name" - assert new_entities_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_entities_descriptor.cache_duration == "10:00:00:00" - assert isinstance(new_entities_descriptor.signature, ds.Signature) - assert isinstance(new_entities_descriptor.extensions, md.Extensions) - assert isinstance(new_entities_descriptor.entity_descriptor[0], - md.EntityDescriptor) - assert isinstance(new_entities_descriptor.entities_descriptor[0], - md.EntitiesDescriptor) - - def testUsingTestData(self): - """Test for entities_descriptor_from_string() using test data.""" - new_entities_descriptor = md.entities_descriptor_from_string( - md_data.TEST_ENTITIES_DESCRIPTOR) - assert new_entities_descriptor.id == "ID" - assert new_entities_descriptor.name == "name" - assert new_entities_descriptor.valid_until == "2008-09-14T01:05:02Z" - assert new_entities_descriptor.cache_duration == "10:00:00:00" - assert isinstance(new_entities_descriptor.signature, ds.Signature) - assert isinstance(new_entities_descriptor.extensions, md.Extensions) - assert isinstance(new_entities_descriptor.entity_descriptor[0], - md.EntityDescriptor) - assert isinstance(new_entities_descriptor.entities_descriptor[0], - md.EntitiesDescriptor) - - diff --git a/tests/test_03_samlp.py b/tests/test_03_samlp.py deleted file mode 100644 index 8e739d6..0000000 --- a/tests/test_03_samlp.py +++ /dev/null @@ -1,535 +0,0 @@ -#!/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 -from saml2 import saml, samlp -import saml2_data, ds_data, samlp_data -import xmldsig as ds - - -class TestAbstractRequest: - - def setup_class(self): - self.ar = samlp.AbstractRequest() - - def testAccessors(self): - """Test for AbstractRequest 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.get_empty_signature() - self.ar.extensions = samlp.Extensions() - - new_ar = samlp.abstract_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) - - def testUsingTestData(self): - """Test for abstract_request_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 TestStatusResponse: - - def setup_class(self): - self.sr = samlp.StatusResponse() - - def testAccessors(self): - """Test for StatusResponse 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.get_empty_signature() - self.sr.extensions = samlp.Extensions() - self.sr.status = samlp.Status() - - new_sr = samlp.status_response_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.get_empty_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.get_empty_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.assertion_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.assertion_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.assertion_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.get_empty_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, 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, samlp.SessionIndex) - assert new_lr.session_index.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.get_empty_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) - diff --git a/tests/test_11_utils.py b/tests/test_11_utils.py deleted file mode 100644 index 7db145c..0000000 --- a/tests/test_11_utils.py +++ /dev/null @@ -1,443 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import zlib -import base64 -import gzip - -from saml2 import utils, saml, samlp, md, make_instance -from saml2.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 = """ -""" - -ERROR_STATUS = """ -Error resolving principal""" - - -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(): - stat = utils.args2dict( - status_code=utils.args2dict(value=samlp.STATUS_SUCCESS)) - status = make_instance( samlp.Status, stat) - status_text = "%s" % status - assert status_text == SUCCESS_STATUS - assert status.status_code.value == samlp.STATUS_SUCCESS - -def test_success_status(): - stat = utils.success_status_factory() - status = make_instance(samlp.Status, stat) - status_text = "%s" % status - assert status_text == SUCCESS_STATUS - assert status.status_code.value == samlp.STATUS_SUCCESS - -def test_error_status(): - stat = utils.args2dict( - status_message=utils.args2dict("Error resolving principal"), - status_code=utils.args2dict( - value=samlp.STATUS_RESPONDER, - status_code=utils.args2dict( - value=samlp.STATUS_UNKNOWN_PRINCIPAL))) - - status_text = "%s" % make_instance( samlp.Status, stat ) - 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) - print stat - status_text = "%s" % make_instance( samlp.Status, 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 = make_instance(saml.Attribute, attr[0]) - print inst - assert inst.name == "surName" - assert len(inst.attribute_value) == 1 - av = inst.attribute_value[0] - assert av.text == "Jeter" - assert av.type == "xs:string" - -def test_attribute_age(): - attr = utils.do_attributes({"age":37}) - - assert len(attr) == 1 - inst = make_instance(saml.Attribute, 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.type == "xs:integer" - -def test_attribute_onoff(): - attr = utils.do_attributes({"onoff":False}) - - assert len(attr) == 1 - inst = make_instance(saml.Attribute, 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.type == "xs:boolean" - -def test_attribute_base64(): - attr = utils.do_attributes({"name":"Selma Lagerlöf"}) - - assert len(attr) == 1 - inst = make_instance(saml.Attribute, attr[0], True) - print inst - assert inst.name == "name" - assert len(inst.attribute_value) == 1 - av = inst.attribute_value[0] - assert av.type == "xs:base64Binary" - assert av.text.strip() == "U2VsbWEgTGFnZXJsw7Zm" - -def test_attribute_statement(): - astat = do_attribute_statement({"surName":"Jeter", - "givenName":"Derek"}) - print astat - statement = make_instance(saml.AttributeStatement,astat) - 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 = make_instance( saml.AudienceRestriction, - utils.args2dict( - audience=utils.args2dict("urn:foo:bar"))) - - assert aud_restr.keyswv() == ["audience"] - assert aud_restr.audience.text == "urn:foo:bar" - -def test_conditions(): - conds_dict = utils.args2dict( - not_before="2009-10-30T07:58:10.852Z", - not_on_or_after="2009-10-30T08:03:10.852Z", - audience_restriction=utils.args2dict( - audience=utils.args2dict("urn:foo:bar"))) - - conditions = make_instance(saml.Conditions, conds_dict) - 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" - adict = utils.args2dict(name="urn:oid:2.5.4.42", - name_format=NAME_FORMAT_URI) - attribute = make_instance(saml.Attribute, adict) - 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(): - adict = utils.args2dict(name="urn:oid:2.5.4.42", - name_format=NAME_FORMAT_URI, - friendly_name="givenName") - attribute = make_instance(saml.Attribute, adict) - 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(): - adict = utils.args2dict(attribute_value="Derek", - name="urn:oid:2.5.4.42", - name_format=NAME_FORMAT_URI, - friendly_name="givenName") - attribute = make_instance(saml.Attribute, adict) - 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(): - adict = utils.args2dict(attribute_value="Derek", - friendly_name="givenName") - attribute = make_instance(saml.Attribute, adict) - 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(): - astat = do_attribute_statement({"vo_attr":"foobar"}) - statement = make_instance(saml.AttributeStatement,astat) - 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(): - astat = do_attribute_statement({"surName":"Jeter", - "givenName":["Derek","Sanderson"]}) - statement = make_instance(saml.AttributeStatement, astat) - 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(): - astat = 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"}) - statement = make_instance(saml.AttributeStatement,astat) - 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(): - adict = utils.args2dict("_aaa", name_id=saml.NAMEID_FORMAT_TRANSIENT) - subject = make_instance(saml.Subject, adict) - 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_args2dict(): - n = utils.args2dict("foo", name_qualifier="urn:mace:example.com:nq") - assert _eq(n.keys(), ["text","name_qualifier"]) - assert n["text"] == "foo" - assert n["name_qualifier"] == "urn:mace:example.com:nq" - -def test_attribute(): - a = utils.args2dict(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.keys(), ["friendly_name","name", "name_format"]) - - a = utils.args2dict(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=utils.args2dict("member@example.com")) - - assert _eq(a.keys(), ["friendly_name","name", "name_format", - "attribute_value"]) - -def test_attribute_statement(): - a = utils.args2dict( - attribute=[ - utils.args2dict(attribute_value="Derek", - friendly_name="givenName"), - utils.args2dict(attribute_value="Jeter", - friendly_name="surName"), - ]) - assert a.keys() == ["attribute"] - assert len(a["attribute"]) == 2 - -def test_subject_confirmation_data(): - s = utils.args2dict( - 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.keys(),["in_response_to","not_before","not_on_or_after", - "recipient", "address"]) - -def test_subject_confirmation(): - s = utils.args2dict( - method="urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser", - base_id="1234", - name_id="abcd", - subject_confirmation_data=utils.args2dict( - in_response_to="_1234567890", - recipient="http://example.com/sp/")) - - assert _eq(s.keys(), - ["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.args2dict( - "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified") - assert a.keys() == ["text"] - assert a["text"] == "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified" - -def test_authn_context(): - accr = utils.args2dict( - "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified") - a = utils.args2dict(authn_context_class_ref=accr) - - assert a.keys() == ["authn_context_class_ref"] - -def test_authn_statement(): - accr = utils.args2dict( - "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified") - ac = utils.args2dict(authn_context_class_ref=accr) - a = utils.args2dict( - authn_instant="2010-03-10T12:33:00Z", - session_index="_12345", - session_not_on_or_after="2010-03-11T12:00:00Z", - authn_context=ac - ) diff --git a/tests/test_20_assertion.py b/tests/test_20_assertion.py index b897474..394ee11 100644 --- a/tests/test_20_assertion.py +++ b/tests/test_20_assertion.py @@ -2,7 +2,7 @@ from saml2 import md, assertion from saml2.saml import Attribute, NAME_FORMAT_URI, AttributeValue from saml2.assertion import Policy, Assertion, filter_on_attributes from saml2.assertion import filter_attribute_value_assertions -from saml2.utils import MissingValue +from saml2.s_utils import MissingValue from saml2 import attribute_converter from py.test import raises @@ -152,21 +152,24 @@ def test_ava_filter_2(): } }} - r = Policy(conf) + policy = Policy(conf) ava = {"givenName":"Derek", "surName": "Jeter", "mail":"derek@example.com"} # I'm filtering away something the SP deems necessary - raises(MissingValue, r.filter, ava, 'urn:mace:umu.se:saml:roland:sp', + + #policy.filter(ava, 'urn:mace:umu.se:saml:roland:sp', [mail], [gn, sn]) + + raises(MissingValue, policy.filter, ava, 'urn:mace:umu.se:saml:roland:sp', [mail], [gn, sn]) ava = {"givenName":"Derek", "surName": "Jeter"} # it wasn't there to begin with - raises(MissingValue, r.filter, ava, 'urn:mace:umu.se:saml:roland:sp', + raises(MissingValue, policy.filter, ava, 'urn:mace:umu.se:saml:roland:sp', [gn,sn,mail]) def test_filter_attribute_value_assertions_0(AVA): diff --git a/tests/test_21_attribute_converter.py b/tests/test_21_attribute_converter.py index 17a51e8..c712715 100644 --- a/tests/test_21_attribute_converter.py +++ b/tests/test_21_attribute_converter.py @@ -57,21 +57,21 @@ class TestAC(): statement = attribute_converter.from_local(self.acs, ava, BASIC_NF) assert statement != None - assert len(statement["attribute"]) == 2 - a0 = statement["attribute"][0] - a1 = statement["attribute"][1] - if a0["friendly_name"] == 'sn': - assert a0["name"] == 'urn:mace:dir:attribute-def:sn' - assert a0["name_format"] == BASIC_NF - assert a1["friendly_name"] == "givenName" - assert a1["name"] == 'urn:mace:dir:attribute-def:givenName' - assert a1["name_format"] == BASIC_NF - elif a0["friendly_name"] == 'givenName': - assert a0["name"] == 'urn:mace:dir:attribute-def:givenName' - assert a0["name_format"] == BASIC_NF - assert a1["friendly_name"] == "sn" - assert a1["name"] == 'urn:mace:dir:attribute-def:sn' - assert a1["name_format"] == BASIC_NF + assert len(statement) == 2 + a0 = statement[0] + a1 = statement[1] + if a0.friendly_name == 'sn': + assert a0.name == 'urn:mace:dir:attribute-def:sn' + assert a0.name_format == BASIC_NF + assert a1.friendly_name == "givenName" + assert a1.name == 'urn:mace:dir:attribute-def:givenName' + assert a1.name_format == BASIC_NF + elif a0.friendly_name == 'givenName': + assert a0.name == 'urn:mace:dir:attribute-def:givenName' + assert a0.name_format == BASIC_NF + assert a1.friendly_name == "sn" + assert a1.name == 'urn:mace:dir:attribute-def:sn' + assert a1.name_format == BASIC_NF else: assert False @@ -80,21 +80,21 @@ class TestAC(): statement = attribute_converter.from_local(self.acs, ava, URI_NF) - assert len(statement["attribute"]) == 2 - a0 = statement["attribute"][0] - a1 = statement["attribute"][1] - if a0["friendly_name"] == 'surname': - assert a0["name"] == 'urn:oid:2.5.4.4' - assert a0["name_format"] == URI_NF - assert a1["friendly_name"] == "givenName" - assert a1["name"] == 'urn:oid:2.5.4.42' - assert a1["name_format"] == URI_NF - elif a0["friendly_name"] == 'givenName': - assert a0["name"] == 'urn:oid:2.5.4.42' - assert a0["name_format"] == URI_NF - assert a1["friendly_name"] == "surname" - assert a1["name"] == 'urn:oid:2.5.4.4' - assert a1["name_format"] == URI_NF + assert len(statement) == 2 + a0 = statement[0] + a1 = statement[1] + if a0.friendly_name == 'surname': + assert a0.name == 'urn:oid:2.5.4.4' + assert a0.name_format == URI_NF + assert a1.friendly_name == "givenName" + assert a1.name == 'urn:oid:2.5.4.42' + assert a1.name_format == URI_NF + elif a0.friendly_name == 'givenName': + assert a0.name == 'urn:oid:2.5.4.42' + assert a0.name_format == URI_NF + assert a1.friendly_name == "surname" + assert a1.name == 'urn:oid:2.5.4.4' + assert a1.name_format == URI_NF else: assert False diff --git a/tests/test_30_metadata.py b/tests/test_30_metadata.py index 4345813..3aec570 100644 --- a/tests/test_30_metadata.py +++ b/tests/test_30_metadata.py @@ -10,7 +10,7 @@ from saml2.attribute_converter import ac_factory from py.test import raises -SWAMI_METADATA = "swamid-kalmar-1.0.xml" +SWAMI_METADATA = "swamid-1.0.xml" INCOMMON_METADATA = "InCommon-metadata.xml" EXAMPLE_METADATA = "metadata_example.xml" SWITCH_METADATA = "metadata.aaitest.xml" @@ -53,16 +53,19 @@ def test_swami_1(): ssocerts = md.certs('https://idp.umu.se/saml2/idp/SSOService.php') print ssocerts assert len(ssocerts) == 1 - print md.wants - assert _eq(md._wants.keys(),['https://connect.sunet.se/shibboleth', - 'https://sp.swamid.se/shibboleth']) - assert _eq(md.wants('https://sp.swamid.se/shibboleth')[1].keys(), - ["eduPersonPrincipalName"]) - assert md.wants('https://sp.swamid.se/shibboleth')[0] == {} + print md._wants.keys() + assert _eq(md._wants.keys(),['https://connect.sunet.se/shibboleth', + 'https://www.diva-portal.org/shibboleth']) + + print md.wants('https://www.diva-portal.org/shibboleth') + assert _eq(md.wants('https://www.diva-portal.org/shibboleth')[1].keys(), + ['mail', 'givenName', 'eduPersonPrincipalName', 'sn', + 'eduPersonScopedAffiliation']) + + assert md.wants('https://connect.sunet.se/shibboleth')[0] == {} assert _eq(md.wants('https://connect.sunet.se/shibboleth')[1].keys(), ['mail', 'givenName', 'eduPersonPrincipalName', 'sn', 'eduPersonScopedAffiliation']) - assert md.wants('https://connect.sunet.se/shibboleth')[0] == {} def test_incommon_1(): md = metadata.MetaData(attrconv=ATTRCONV) @@ -130,8 +133,9 @@ def test_sp_metadata(): print md.entity assert len(md.entity) == 1 assert md.entity.keys() == ['urn:mace:umu.se:saml:roland:sp'] - assert md.entity['urn:mace:umu.se:saml:roland:sp'].keys() == [ - 'valid_until',"organization","sp_sso"] + assert _eq(md.entity['urn:mace:umu.se:saml:roland:sp'].keys(), [ + 'valid_until',"organization","sp_sso", + 'contact_person']) print md.entity['urn:mace:umu.se:saml:roland:sp']["sp_sso"][0].keyswv() (req,opt) = md.attribute_consumer('urn:mace:umu.se:saml:roland:sp') print req @@ -174,7 +178,7 @@ def test_construct_organisation_name(): md.OrganizationName, o, "organization_name") print o assert str(o) == """ -Exempel AB""" +Exempel AB""" def test_make_int_value(): val = make_vals( 1, saml.AttributeValue, part=True) @@ -260,10 +264,11 @@ def test_construct_entity_descr_1(): assert ed.entity_id == "urn:mace:catalogix.se:sp1" org = ed.organization - assert _eq(org.keyswv(), ["organization_name","organization_url"]) - assert len(org.organization_name) == 1 - assert org.organization_name[0].text == "Catalogix" - assert org.organization_url[0].text == "http://www.catalogix.se/" + assert len(org) == 1 + assert _eq(org[0].keyswv(), ["organization_name","organization_url"]) + assert len(org[0].organization_name) == 1 + assert org[0].organization_name[0].text == "Catalogix" + assert org[0].organization_url[0].text == "http://www.catalogix.se/" def test_construct_entity_descr_2(): ed = make_instance(md.EntityDescriptor, @@ -281,10 +286,11 @@ def test_construct_entity_descr_2(): assert _eq(ed.keyswv(), ["entity_id", "contact_person", "organization"]) assert ed.entity_id == "urn:mace:catalogix.se:sp1" org = ed.organization - assert _eq(org.keyswv(), ["organization_name", "organization_url"]) - assert len(org.organization_name) == 1 - assert org.organization_name[0].text == "Catalogix" - assert org.organization_url[0].text == "http://www.catalogix.se/" + assert len(org) == 1 + assert _eq(org[0].keyswv(), ["organization_name", "organization_url"]) + assert len(org[0].organization_name) == 1 + assert org[0].organization_name[0].text == "Catalogix" + assert org[0].organization_url[0].text == "http://www.catalogix.se/" assert len(ed.contact_person) == 1 c = ed.contact_person[0] assert c.given_name.text == "Roland" diff --git a/tests/test_31_config.py b/tests/test_31_config.py index 0bb6b6b..3d490c9 100644 --- a/tests/test_31_config.py +++ b/tests/test_31_config.py @@ -9,7 +9,9 @@ sp1 = { "entityid" : "urn:mace:umu.se:saml:roland:sp", "service": { "sp": { - "url" : "http://lingon.catalogix.se:8087/", + "endpoints" : { + "assertion_consumer_service" : ["http://lingon.catalogix.se:8087/"], + }, "name": "test", "idp" : { "urn:mace:example.com:saml:roland:idp":None, @@ -36,7 +38,9 @@ sp2 = { "service": { "sp":{ "name" : "Rolands SP", - "url" : "http://localhost:8087/", + "endpoints" : { + "assertion_consumer_service" : ["http://lingon.catalogix.se:8087/"], + }, "required_attributes": ["surName", "givenName", "mail"], "optional_attributes": ["title"], "idp": { @@ -52,7 +56,9 @@ IDP1 = { "service": { "idp":{ "name" : "Rolands IdP", - "url" : "http://localhost:8088/", + "endpoints": { + "single_sign_on_service" : ["http://localhost:8088/"], + }, "assertions":{ "default": { "attribute_restrictions": { @@ -79,7 +85,7 @@ def test_1(): service = c["service"] assert service.keys() == ["sp"] sp = service["sp"] - assert _eq(sp.keys(),["url","name","idp"]) + assert _eq(sp.keys(),["endpoints","name","idp"]) md = c["metadata"] assert isinstance(md, MetaData) @@ -94,7 +100,7 @@ def test_2(): service = c["service"] assert service.keys() == ["sp"] sp = service["sp"] - assert _eq(sp.keys(),['url', 'idp', 'optional_attributes', 'name', + assert _eq(sp.keys(),['endpoints', 'idp', 'optional_attributes', 'name', 'required_attributes']) assert len(sp["idp"]) == 1 @@ -111,7 +117,9 @@ def test_missing_must(): no_entity_id = { "service": { "sp": { - "url" : "http://lingon.catalogix.se:8087/", + "endpoints" : { + "assertion_consumer_service" : ["http://lingon.catalogix.se:8087/"], + }, "name" : "test" } }, @@ -122,7 +130,9 @@ def test_missing_must(): "entityid" : "urn:mace:umu.se:saml:roland:sp", "service": { "sp": { - "url" : "http://lingon.catalogix.se:8087/", + "endpoints" : { + "assertion_consumer_service" : ["http://lingon.catalogix.se:8087/"], + }, "name" : "test" } }, @@ -138,7 +148,9 @@ def test_minimum(): "entityid" : "urn:mace:example.com:saml:roland:sp", "service": { "sp": { - "url" : "http://sp.example.org/", + "endpoints" : { + "assertion_consumer_service" : ["http://sp.example.org/"], + }, "name" : "test", "idp": { "" : "https://example.com/idp/SSOService.php", @@ -157,8 +169,15 @@ def test_idp(): print c assert c.services() == ["idp"] - assert c.idp_url() == "http://localhost:8088/" + assert c.endpoint("idp", "single_sign_on_service") == ['http://localhost:8088/'] attribute_restrictions = c.idp_policy().get_attribute_restriction("") assert attribute_restrictions["eduPersonAffiliation"][0].match("staff") + +def test_wayf(): + c = Config().load_file("server.config") + + idps = c.get_available_idps() + assert idps == [('urn:mace:example.com:saml:roland:idp', 'Example Co')] + \ No newline at end of file diff --git a/tests/test_33_identifier.py b/tests/test_33_identifier.py index 9f2b292..7a114d1 100644 --- a/tests/test_33_identifier.py +++ b/tests/test_33_identifier.py @@ -14,7 +14,9 @@ CONFIG = Config().load({ "entityid" : "urn:mace:example.com:idp:2", "service": { "idp": { - "url" : "http://idp.example.org/", + "endpoints" : { + "single_sign_on_service" : ["http://idp.example.org/"], + }, "name" : "test", "assertions": { "default": { @@ -69,15 +71,17 @@ class TestIdentifier(): nameid = self.id.construct_nameid(policy, "foobar", "urn:mace:example.com:sp:1") - assert _eq(nameid.keys(), ['text', 'sp_name_qualifier', 'format']) - assert nameid["sp_name_qualifier"] == CONFIG["entityid"] - assert nameid["format"] == NAMEID_FORMAT_PERSISTENT + assert _eq(nameid.keys(), ['text', 'sp_provided_id', + 'sp_name_qualifier', 'name_qualifier', 'format']) + assert _eq(nameid.keyswv(), ['format', 'text', 'sp_name_qualifier']) + assert nameid.sp_name_qualifier == CONFIG["entityid"] + assert nameid.format == NAMEID_FORMAT_PERSISTENT nameid_2 = self.id.construct_nameid(policy, "foobar", "urn:mace:example.com:sp:1") - assert nameid == nameid_2 - assert nameid["text"] == nameid_2["text"] + assert nameid != nameid_2 + assert nameid.text == nameid_2.text def test_transient_1(self): policy = Policy({ @@ -92,8 +96,8 @@ class TestIdentifier(): nameid = self.id.construct_nameid(policy, "foobar", "urn:mace:example.com:sp:1") - assert _eq(nameid.keys(), ['text', 'format']) - assert nameid["format"] == NAMEID_FORMAT_TRANSIENT + assert _eq(nameid.keyswv(), ['text', 'format']) + assert nameid.format == NAMEID_FORMAT_TRANSIENT def test_vo_1(self): policy = Policy({ @@ -112,11 +116,11 @@ class TestIdentifier(): {"uid": "foobar01"}, name_id_policy) - assert _eq(nameid.keys(), ['text', 'sp_name_qualifier', 'format']) - assert nameid["sp_name_qualifier"] == 'http://vo.example.org/biomed' - assert nameid["format"] == \ + assert _eq(nameid.keyswv(), ['text', 'sp_name_qualifier', 'format']) + assert nameid.sp_name_qualifier == 'http://vo.example.org/biomed' + assert nameid.format == \ CONFIG.vo_conf('http://vo.example.org/biomed')["nameid_format"] - assert nameid["text"] == "foobar01" + assert nameid.text == "foobar01" def test_vo_2(self): policy = Policy({ @@ -136,8 +140,8 @@ class TestIdentifier(): {"uid": "foobar01"}, name_id_policy) - assert _eq(nameid.keys(), ['text', 'sp_name_qualifier', 'format']) - assert nameid["sp_name_qualifier"] == 'http://vo.example.org/design' - assert nameid["format"] == NAMEID_FORMAT_PERSISTENT - assert nameid["text"] != "foobar01" + assert _eq(nameid.keyswv(), ['text', 'sp_name_qualifier', 'format']) + assert nameid.sp_name_qualifier == 'http://vo.example.org/design' + assert nameid.format == NAMEID_FORMAT_PERSISTENT + assert nameid.text != "foobar01" diff --git a/tests/test_40_sigver.py b/tests/test_40_sigver.py index 74cff64..454fd68 100644 --- a/tests/test_40_sigver.py +++ b/tests/test_40_sigver.py @@ -4,9 +4,10 @@ import os import base64 from saml2 import sigver, make_instance -from saml2 import utils, class_name +from saml2 import class_name from saml2 import time_util from saml2 import saml, samlp +from saml2.s_utils import factory, do_attribute_statement import xmldsig as ds from py.test import raises @@ -21,11 +22,11 @@ PRIV_KEY = "test.key" def _eq(l1,l2): return set(l1) == set(l2) -SIGNED_VALUE= """AS1kHHtA4eTOU2XLTWhLMSJQ6V+TSDymRoTF78CqjrYURNLk9wjdPjAReNn9eykv -ryFiHNk0p9wMBknha5pH8aeCI/LmcVhLa5xteGZrtE/Udh5vv8z4kRQX51Uz/5x8 -ToiobGw83MEW6A0dRUn0O20NBMMTaFZZPXye7RvVlHY=""" +SIGNED_VALUE= """kMuyOK17nyp4CbA1v7KE32rX4+NQQ8EvdglTK61uIMEo3ax0PgFU7bgZGey+Aj8H +hTPVyAzWmBDxHpSCFe050PTtNoKHx7nXprLfhuQXsPq8s0KBoZR+2qYfVCkWYVX7 +T3zG/Tn+fesBA1zLo4lYdAovol7C35KAsAWoknmZdOE=""" -DIGEST_VALUE = "WFRXmImfoO3M6JOLE6BGGpU9Ud0=" +DIGEST_VALUE = "SXw3kqTf+PtTiUnI8nQ6xmrM3qw=" def get_xmlsec(): for path in os.environ["PATH"].split(":"): @@ -94,24 +95,16 @@ class TestSecurity(): self.sec = sigver.SecurityContext(get_xmlsec(), PRIV_KEY, "pem", PUB_KEY, "pem", debug=1) - self._assertion = { - "version": "2.0", - "id": "11111", - "issue_instant": "2009-10-30T13:20:28Z", - "signature": sigver.pre_signature_part("11111", self.sec.my_cert, - 1), - "attribute_statement": { - "attribute": [{ - "friendly_name": "surName", - "attribute_value": "Foo", - }, - { - "friendly_name": "givenName", - "attribute_value": "Bar", - } - ] - } - } + self._assertion = factory( saml.Assertion, + version="2.0", + id="11111", + issue_instant="2009-10-30T13:20:28Z", + signature=sigver.pre_signature_part("11111", self.sec.my_cert, 1), + attribute_statement=do_attribute_statement({ + ("","","surName"): ("Foo",""), + ("","","givenName") :("Bar",""), + }) + ) def test_verify_1(self): xml_response = open(SIGNED).read() @@ -130,10 +123,10 @@ class TestSecurity(): xml_response) def test_sign_assertion(self): - ass = make_instance(saml.Assertion, self._assertion) - + ass = self._assertion + print ass sign_ass = self.sec.sign_assertion_using_xmlsec("%s" % ass, nodeid=ass.id) - + print sign_ass sass = saml.assertion_from_string(sign_ass) print sass assert _eq(sass.keyswv(), ['attribute_statement', 'issue_instant', @@ -144,15 +137,18 @@ class TestSecurity(): sig = sass.signature assert sig.signature_value.text == SIGNED_VALUE assert len(sig.signed_info.reference) == 1 - assert len(sig.signed_info.reference[0].digest_value) == 1 - assert sig.signed_info.reference[0].digest_value[0].text == DIGEST_VALUE + assert sig.signed_info.reference[0].digest_value + assert sig.signed_info.reference[0].digest_value.text == DIGEST_VALUE def test_sign_response(self): - s_response = sigver.signed_instance_factory(samlp.Response, { - "assertion" : self._assertion, - "id": "22222", - "signature": sigver.pre_signature_part("22222"), - }, self.sec) + response = factory(samlp.Response, + assertion=self._assertion, + id="22222", + signature=sigver.pre_signature_part("22222", self.sec.my_cert)) + + to_sign = [(class_name(self._assertion), self._assertion.id), + (class_name(response), response.id)] + s_response = sigver.signed_instance_factory( response, self.sec, to_sign) assert s_response != None print s_response @@ -166,38 +162,34 @@ class TestSecurity(): assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) sig = sass.signature - assert sig.signature_value.text == """xObs8g6Kr11NopsCxv9IXPQZ4Qfxag3zZrxcza+NBZwQ2JIXEw6vQDmu/OG+EgUP\n2miVoAY4nbklsiwXZfjXYU3OOUDJr7UDhAHUuki/kcKCV6SMEUFlOcEzDFVg+Fr+\nFsPJhsmit5uRRP5rYA92y1fKf42vViw8LFj+LqlTv2Y=""" + assert sig.signature_value.text == """upeKPE1pkzXLy9BvKFOSTnjn4du59lQQ74TN5CqDGae9D21uY/zLuOWql7LiSTSi\nC945F0WrOvG7s0eZnpuNPZobdfdeCOffCMMrq5RQ2+abPFBamkjmceuEKGdO5PWQ\nt7B1GkzXAMMgeMuU+YmvIJkHbbv5Yn6M0/ICE/COaKQ=""" assert len(sig.signed_info.reference) == 1 - assert len(sig.signed_info.reference[0].digest_value) == 1 - digest = sig.signed_info.reference[0].digest_value[0].text - assert digest == """z6O3mlLmX1a6Wk1F4cgMsAXdA6Q=""" + assert sig.signed_info.reference[0].digest_value + digest = sig.signed_info.reference[0].digest_value.text + assert digest == """uX92C/YDroqITDfDY1IeekGtZac=""" def test_sign_response_2(self): - assertion2 = { - "version": "2.0", - "id": "11122", - "issue_instant": "2009-10-30T13:20:28Z", - "signature": sigver.pre_signature_part("11122"), - "attribute_statement": { - "attribute": [{ - "friendly_name": "surName", - "attribute_value": "Fox", - }, - { - "friendly_name": "givenName", - "attribute_value": "Bear", - } - ] - } - } + assertion2 = factory( saml.Assertion, + version= "2.0", + id= "11122", + issue_instant= "2009-10-30T13:20:28Z", + signature= sigver.pre_signature_part("11122", self.sec.my_cert), + attribute_statement=do_attribute_statement({ + ("","","surName"): ("Fox",""), + ("","","givenName") :("Bear",""), + }) + ) + response = factory(samlp.Response, + assertion=assertion2, + id="22233", + signature=sigver.pre_signature_part("22233")) + + to_sign = [(class_name(assertion2), assertion2.id), + (class_name(response), response.id)] + + s_response = sigver.signed_instance_factory( response, self.sec, to_sign) - s_response = sigver.signed_instance_factory(samlp.Response, { - "assertion" : [self._assertion,assertion2], - "id": "22233", - "signature": sigver.pre_signature_part("22233"), - }, self.sec) - assert s_response != None print s_response print @@ -207,23 +199,26 @@ class TestSecurity(): assert _eq(sass.keyswv(), ['attribute_statement', 'issue_instant', 'version', 'signature', 'id']) assert sass.version == "2.0" - assert sass.id == "11111" + assert sass.id == "11122" assert time_util.str_to_time(sass.issue_instant) sig = sass.signature - assert sig.signature_value.text == """xObs8g6Kr11NopsCxv9IXPQZ4Qfxag3zZrxcza+NBZwQ2JIXEw6vQDmu/OG+EgUP\n2miVoAY4nbklsiwXZfjXYU3OOUDJr7UDhAHUuki/kcKCV6SMEUFlOcEzDFVg+Fr+\nFsPJhsmit5uRRP5rYA92y1fKf42vViw8LFj+LqlTv2Y=""" + assert sig.signature_value.text == """xHECLk1jj4NBvk1jhGrb2mwnrLFKXk6JN3NogjMVMtnnarg9vtk7jYzy1M9RPWdj\nRSa2Jph7yVZJENm4bGuBkT91w+FYm2X4jREULPUsnupPHTQyhJEVZ07EhnluOWa3\n95KkqnZ5gbnTxn1ZvpsANzThLmYY3eSGzNXz+S7758M=""" assert len(sig.signed_info.reference) == 1 - assert len(sig.signed_info.reference[0].digest_value) == 1 - digest = sig.signed_info.reference[0].digest_value[0].text - assert digest == """z6O3mlLmX1a6Wk1F4cgMsAXdA6Q=""" + assert sig.signed_info.reference[0].digest_value + digest = sig.signed_info.reference[0].digest_value.text + assert digest == """l36wHa6Lyed9ZeAZ3jFL77wPVQ4=""" def test_sign_verify(self): - s_response = sigver.signed_instance_factory(samlp.Response, { - "assertion" : self._assertion, - "id": "22222", - "signature": sigver.pre_signature_part("22222", - self.sec.my_cert), - }, self.sec) + response = factory(samlp.Response, + assertion=self._assertion, + id="22233", + signature=sigver.pre_signature_part("22233", self.sec.my_cert)) + + to_sign = [(class_name(self._assertion), self._assertion.id), + (class_name(response), response.id)] + + s_response = sigver.signed_instance_factory(response, self.sec, to_sign) print s_response res = self.sec.verify_signature("%s" % s_response, @@ -233,16 +228,25 @@ class TestSecurity(): assert res def test_sign_verify_with_cert_from_instance(self): - s_response = sigver.signed_instance_factory(samlp.Response, { - "assertion" : self._assertion, - "id": "22222", - "signature": sigver.pre_signature_part("22222", - self.sec.my_cert), - }, self.sec) - - print s_response + response = factory(samlp.Response, + assertion=self._assertion, + id="22222", + signature=sigver.pre_signature_part("22222", self.sec.my_cert)) + to_sign = [(class_name(self._assertion), self._assertion.id), + (class_name(response), response.id)] + + s_response = sigver.signed_instance_factory(response, self.sec, to_sign) + + print s_response.keyswv() + print s_response.signature.keyswv() + print s_response.signature.key_info.keyswv() + ci = "".join(sigver.cert_from_instance(s_response)[0].split()) + + print ci + print self.sec.my_cert + assert ci == self.sec.my_cert res = self.sec.verify_signature("%s" % s_response, @@ -254,26 +258,19 @@ class TestSecurity(): assert res == s_response def test_sign_verify_assertion_with_cert_from_instance(self): - assertion = { - "version": "2.0", - "id": "11111", - "issue_instant": "2009-10-30T13:20:28Z", - "signature": sigver.pre_signature_part("11111", self.sec.my_cert), - "attribute_statement": { - "attribute": [{ - "friendly_name": "surName", - "attribute_value": "Foo", - }, - { - "friendly_name": "givenName", - "attribute_value": "Bar", - } - ] - } - } + assertion = factory( saml.Assertion, + version= "2.0", + id= "11100", + issue_instant= "2009-10-30T13:20:28Z", + signature= sigver.pre_signature_part("11100", self.sec.my_cert), + attribute_statement=do_attribute_statement({ + ("","","surName"): ("Fox",""), + ("","","givenName") :("Bear",""), + }) + ) - s_assertion = sigver.signed_instance_factory(saml.Assertion, - assertion, self.sec) + to_sign = [(class_name(assertion), assertion.id)] + s_assertion = sigver.signed_instance_factory(assertion, self.sec, to_sign) print s_assertion ci = "".join(sigver.cert_from_instance(s_assertion)[0].split()) @@ -289,30 +286,25 @@ class TestSecurity(): assert res def test_exception_sign_verify_with_cert_from_instance(self): - assertion = { - "version": "2.0", - "id": "11111", - "issue_instant": "2009-10-30T13:20:28Z", - #"signature": sigver.pre_signature_part("11111"), - "attribute_statement": { - "attribute": [{ - "friendly_name": "surName", - "attribute_value": "Foo", - }, - { - "friendly_name": "givenName", - "attribute_value": "Bar", - } - ] - } - } + assertion = factory( saml.Assertion, + version= "2.0", + id= "11100", + issue_instant= "2009-10-30T13:20:28Z", + #signature= sigver.pre_signature_part("11100", self.sec.my_cert), + attribute_statement=do_attribute_statement({ + ("","","surName"): ("Foo",""), + ("","","givenName") :("Bar",""), + }) + ) - s_response = sigver.signed_instance_factory(samlp.Response, { - "assertion" : assertion, - "id": "22222", - "signature": sigver.pre_signature_part("22222", - self.sec.my_cert), - }, self.sec) + response = factory(samlp.Response, + assertion=assertion, + id="22222", + signature=sigver.pre_signature_part("22222", self.sec.my_cert)) + + to_sign = [(class_name(response), response.id)] + + s_response = sigver.signed_instance_factory(response, self.sec, to_sign) # Change something that should make everything fail @@ -320,16 +312,3 @@ class TestSecurity(): raises(sigver.SignatureError, self.sec._check_signature, "%s" % s_response, s_response, class_name(s_response)) -# def test_sign_verify_assertion_in_response(self): -# s_response = sigver.signed_instance_factory(samlp.Response, { -# "assertion" : self._assertion, -# "id": "22222", -# "signature": sigver.pre_signature_part("22222", -# self.sec.my_cert, 2), -# }, self.sec) -# -# print s_response -# res = self.sec.correctly_signed_response("%s" % s_response) -# -# print res -# assert res diff --git a/tests/test_41_xmldsig.py b/tests/test_41_xmldsig.py deleted file mode 100644 index 44c80e5..0000000 --- a/tests/test_41_xmldsig.py +++ /dev/null @@ -1,655 +0,0 @@ -#!/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.identifier = "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.identifier == "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.identifier == "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.X509IssuerSerial() - - def testAccessors(self): - """Test for X509IssuerSerial accessors""" - self.x509_issuer_serial.x509_issuer_name = ds.X509IssuerName( - text="issuer name") - self.x509_issuer_serial.x509_issuer_number = ds.X509IssuerNumber(text="1") - new_x509_issuer_serial = ds.x509_issuer_serial_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_issuer_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_issuer_number.text.strip() == "1" - - -class TestX509Data: - - def setup_class(self): - self.x509_data = ds.X509Data() - - def testAccessors(self): - """Test for X509Data accessors""" - self.x509_data.x509_issuer_serial.append(ds.x509_issuer_serial_from_string( - ds_data.TEST_X509_ISSUER_SERIAL)) - 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()) - 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) - - 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.xpath.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.xpath[0], ds.XPath) - assert new_transform.xpath[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.xpath[0], ds.XPath) - assert new_transform.xpath[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].xpath[0].text.strip() == "xpath" - assert new_transforms.transform[1].xpath[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].xpath[0].text.strip() == "xpath" - assert new_transforms.transform[1].xpath[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.append(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[0], 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[0], 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.DsP(text="p") - self.dsa_key_value.q = ds.DsQ(text="q") - self.dsa_key_value.g = ds.DsG(text="g") - self.dsa_key_value.y = ds.DsY(text="y") - self.dsa_key_value.j = ds.DsJ(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.DsP) - assert isinstance(new_dsa_key_value.q, ds.DsQ) - assert isinstance(new_dsa_key_value.g, ds.DsG) - assert isinstance(new_dsa_key_value.y, ds.DsY) - assert isinstance(new_dsa_key_value.j, ds.DsJ) - 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.DsP) - assert isinstance(new_dsa_key_value.q, ds.DsQ) - assert isinstance(new_dsa_key_value.g, ds.DsG) - assert isinstance(new_dsa_key_value.y, ds.DsY) - assert isinstance(new_dsa_key_value.j, ds.DsJ) - 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.identifier = "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.identifier == "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.identifier == "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.append(ds.transforms_from_string( - ds_data.TEST_TRANSFORMS)) - self.reference.digest_method.append(ds.digest_method_from_string( - ds_data.TEST_DIGEST_METHOD)) - self.reference.digest_value.append(ds.digest_value_from_string( - ds_data.TEST_DIGEST_VALUE)) - self.reference.identifier = "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[0], ds.Transforms) - assert isinstance(new_reference.digest_method[0], ds.DigestMethod) - assert isinstance(new_reference.digest_value[0], ds.DigestValue) - assert new_reference.identifier == "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[0], ds.Transforms) - assert isinstance(new_reference.digest_method[0], ds.DigestMethod) - assert isinstance(new_reference.digest_value[0], ds.DigestValue) - assert new_reference.identifier == "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.identifier = "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.identifier == "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.identifier == "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.identifier = "id" - self.signature_value.text = "signature value" - new_signature_value = ds.signature_value_from_string( - self.signature_value.to_string()) - assert new_signature_value.identifier == "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.identifier == "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() diff --git a/tests/test_42_xmlenc.py b/tests/test_42_xmlenc.py deleted file mode 100644 index 668bdb2..0000000 --- a/tests/test_42_xmlenc.py +++ /dev/null @@ -1,175 +0,0 @@ -import saml2 -import xmlenc -import xmldsig - -data1 = """ - - - A23B45C56 - -""" - -def test_1(): - ed = xmlenc.encrypted_data_from_string(data1) - assert ed - assert ed.mime_type == "text/xml" - assert len(ed.cipher_data) == 1 - cd = ed.cipher_data[0] - assert len(cd.cipher_value) == 1 - assert cd.cipher_value[0].text == "A23B45C56" - -data2 = """ - - - John Smith - - DEADBEEF -""" - -def test_2(): - ed = xmlenc.encrypted_data_from_string(data2) - assert ed - print ed - assert ed.typ == "http://www.w3.org/2001/04/xmlenc#Element" - assert len(ed.encryption_method) == 1 - em = ed.encryption_method[0] - assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc' - assert len(ed.key_info) == 1 - ki = ed.key_info[0] - assert ki.key_name[0].text == "John Smith" - assert len(ed.cipher_data) == 1 - cd = ed.cipher_data[0] - assert len(cd.cipher_value) == 1 - assert cd.cipher_value[0].text == "DEADBEEF" - -data3 = """ - - - - Sally Doe - - DEADBEEF -""" - -def test_3(): - ed = xmlenc.encrypted_data_from_string(data3) - assert ed - print ed - assert len(ed.encryption_method) == 1 - em = ed.encryption_method[0] - assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#aes128-cbc' - assert len(ed.key_info) == 1 - ki = ed.key_info[0] - 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 len(ed.cipher_data) == 1 - cd = ed.cipher_data[0] - assert len(cd.cipher_value) == 1 - assert cd.cipher_value[0].text == "DEADBEEF" - -data4 = """ - - - John Smith - - xyzabc - - - - Sally Doe -""" - -def test_4(): - ek = xmlenc.encrypted_key_from_string(data4) - assert ek - print ek - assert len(ek.encryption_method) == 1 - em = ek.encryption_method[0] - assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#rsa-1_5' - assert len(ek.key_info) == 1 - ki = ek.key_info[0] - assert ki.key_name[0].text == "John Smith" - assert len(ek.reference_list) == 1 - rl = ek.reference_list[0] - assert len(rl.data_reference) - dr = rl.data_reference[0] - assert dr.uri == "#ED" - assert len(ek.cipher_data) == 1 - cd = ek.cipher_data[0] - assert len(cd.cipher_value) == 1 - assert cd.cipher_value[0].text == "xyzabc" - -data5 = """ - - - - self::text()[parent::rep:CipherValue[@Id="example1"]] - - - - -""" - -def test_5(): - cr = xmlenc.cipher_reference_from_string(data5) - assert cr - print cr - assert len(cr.transforms) == 1 - trs = cr.transforms[0] - 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.xpath) == 1 - xp = tr.xpath[0] - assert xp.text.strip() == """self::text()[parent::rep:CipherValue[@Id="example1"]]""" - - -data6 = """ - - - - - self::xenc:EncryptedData[@Id="example1"] - - - - -""" - -def test_6(): - rl = xmlenc.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.xpath) == 1 - assert tr.xpath[0].text.strip() == """self::xenc:EncryptedData[@Id="example1"]""" - \ No newline at end of file diff --git a/tests/test_44_authnresp.py b/tests/test_44_authnresp.py index f9e831e..6519055 100644 --- a/tests/test_44_authnresp.py +++ b/tests/test_44_authnresp.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- from saml2 import samlp, BINDING_HTTP_POST -from saml2 import saml, utils, config, class_name, make_instance +from saml2 import saml, config, class_name, make_instance from saml2.server import Server from saml2.authnresponse import authn_response @@ -55,6 +55,7 @@ class TestAuthnResponse: assert self.ar.came_from == 'http://localhost:8088/sso' assert self.ar.session_id() == "12" assert self.ar.ava == {'eduPersonEntitlement': ['Jeter'] } + assert self.ar.name_id assert self.ar.issuer() == 'urn:mace:example.com:saml:roland:idp' def test_verify_signed_1(self): @@ -72,18 +73,20 @@ class TestAuthnResponse: assert self.ar.session_id() == "12" assert self.ar.ava == {'eduPersonEntitlement': ['Jeter'] } assert self.ar.issuer() == 'urn:mace:example.com:saml:roland:idp' + assert self.ar.name_id def test_parse_2(self): xml_response = open(XML_RESPONSE_FILE).read() ID = "bahigehogffohiphlfmplepdpcohkhhmheppcdie" self.ar.outstanding_queries = {ID: "http://localhost:8088/foo"} self.ar.requestor = "xenosmilus.umdc.umu.se" - self.ar.timeslack = 20000000 - print self.ar.__dict__ + # roughly a year, should create the response on the fly + self.ar.timeslack = 31536000 self.ar.loads(xml_response, decode=False) self.ar.verify() - print self.ar + print self.ar.__dict__ assert self.ar.came_from == 'http://localhost:8088/foo' assert self.ar.session_id() == ID + assert self.ar.name_id diff --git a/tests/test_50_server.py b/tests/test_50_server.py index 8f42440..c10ae4a 100644 --- a/tests/test_50_server.py +++ b/tests/test_50_server.py @@ -3,9 +3,10 @@ from saml2.server import Server, Identifier from saml2 import server, make_instance -from saml2 import samlp, saml, client, utils, config -from saml2.utils import OtherError -from saml2.utils import do_attribute_statement +from saml2 import samlp, saml, client, config +from saml2 import s_utils +from saml2.s_utils import OtherError +from saml2.s_utils import do_attribute_statement, factory from py.test import raises import shelve import re @@ -25,7 +26,7 @@ class TestServer1(): self.client = client.Saml2Client({},conf) def test_issuer(self): - issuer = make_instance( saml.Issuer, self.server.issuer()) + issuer = self.server.issuer() assert isinstance(issuer, saml.Issuer) assert _eq(issuer.keyswv(), ["text","format"]) assert issuer.format == saml.NAMEID_FORMAT_ENTITY @@ -33,27 +34,24 @@ class TestServer1(): def test_assertion(self): - tmp = utils.assertion_factory( - subject= utils.args2dict("_aaa", - name_id=saml.NAMEID_FORMAT_TRANSIENT), - attribute_statement = utils.args2dict( - attribute=[ - utils.args2dict(attribute_value="Derek", - friendly_name="givenName"), - utils.args2dict(attribute_value="Jeter", - friendly_name="surName"), - ]), + assertion = s_utils.assertion_factory( + subject= factory(saml.Subject, text="_aaa", + name_id=factory(saml.NameID, + format=saml.NAMEID_FORMAT_TRANSIENT)), + attribute_statement = do_attribute_statement({ + ("","","surName"): ("Jeter",""), + ("","","givenName") :("Derek",""), + }), issuer=self.server.issuer(), ) - assertion = make_instance(saml.Assertion, tmp) assert _eq(assertion.keyswv(),['attribute_statement', 'issuer', 'id', 'subject', 'issue_instant', 'version']) assert assertion.version == "2.0" assert assertion.issuer.text == "urn:mace:example.com:saml:roland:idp" # - assert len(assertion.attribute_statement) == 1 - attribute_statement = assertion.attribute_statement[0] + assert assertion.attribute_statement + attribute_statement = assertion.attribute_statement assert len(attribute_statement.attribute) == 2 attr0 = attribute_statement.attribute[0] attr1 = attribute_statement.attribute[1] @@ -70,28 +68,25 @@ class TestServer1(): subject = assertion.subject assert _eq(subject.keyswv(),["text", "name_id"]) assert subject.text == "_aaa" - assert subject.name_id.text == saml.NAMEID_FORMAT_TRANSIENT + assert subject.name_id.format == saml.NAMEID_FORMAT_TRANSIENT def test_response(self): - tmp = utils.response_factory( + response = s_utils.response_factory( in_response_to="_012345", destination="https:#www.example.com", - status=utils.success_status_factory(), - assertion=utils.assertion_factory( - subject = utils.args2dict("_aaa", + status=s_utils.success_status_factory(), + assertion=s_utils.assertion_factory( + subject = factory( saml.Subject, text="_aaa", name_id=saml.NAMEID_FORMAT_TRANSIENT), - attribute_statement = [ - utils.args2dict(attribute_value="Derek", - friendly_name="givenName"), - utils.args2dict(attribute_value="Jeter", - friendly_name="surName"), - ], + attribute_statement = do_attribute_statement({ + ("","","surName"): ("Jeter",""), + ("","","givenName") :("Derek",""), + }), issuer=self.server.issuer(), ), issuer=self.server.issuer(), ) - response = make_instance(samlp.Response, tmp) print response.keyswv() assert _eq(response.keyswv(),['destination', 'assertion','status', 'in_response_to', 'issue_instant', @@ -114,9 +109,9 @@ class TestServer1(): my_name = "My real name", ) - intermed = utils.deflate_and_base64_encode(authn_request) + intermed = s_utils.deflate_and_base64_encode(authn_request) # should raise an error because faulty spentityid - raises(OtherError,self.server.parse_authn_request,intermed) + raises(OtherError, self.server.parse_authn_request, intermed) def test_parse_faulty_request_to_err_status(self): authn_request = self.client.authn_request( @@ -127,14 +122,13 @@ class TestServer1(): my_name = "My real name", ) - intermed = utils.deflate_and_base64_encode(authn_request) + intermed = s_utils.deflate_and_base64_encode(authn_request) try: self.server.parse_authn_request(intermed) status = None except OtherError, oe: print oe.args - status = make_instance(samlp.Status, - utils.status_from_exception_factory(oe)) + status = s_utils.status_from_exception_factory(oe) assert status print status @@ -156,8 +150,9 @@ class TestServer1(): ) print authn_request - intermed = utils.deflate_and_base64_encode(authn_request) + intermed = s_utils.deflate_and_base64_encode(authn_request) response = self.server.parse_authn_request(intermed) + # returns a dictionary print response assert response["consumer_url"] == "http://localhost:8087/" assert response["id"] == "1" @@ -185,12 +180,13 @@ class TestServer1(): assert resp.status assert resp.status.status_code.value == samlp.STATUS_SUCCESS assert resp.assertion - assert len(resp.assertion) == 1 - assertion = resp.assertion[0] - assert len(assertion.authn_statement) == 1 + assert resp.assertion + assertion = resp.assertion + print assertion + assert assertion.authn_statement assert assertion.conditions - assert len(assertion.attribute_statement) == 1 - attribute_statement = assertion.attribute_statement[0] + assert assertion.attribute_statement + attribute_statement = assertion.attribute_statement print attribute_statement assert len(attribute_statement.attribute) == 1 attribute = attribute_statement.attribute[0] @@ -200,11 +196,11 @@ class TestServer1(): assert attribute.name_format == "urn:oasis:names:tc:SAML:2.0:attrname-format:uri" value = attribute.attribute_value[0] assert value.text.strip() == "Short stop" - assert value.type == "xs:string" + assert value.get_type() == "xs:string" assert assertion.subject assert assertion.subject.name_id - assert len(assertion.subject.subject_confirmation) == 1 - confirmation = assertion.subject.subject_confirmation[0] + assert assertion.subject.subject_confirmation + confirmation = assertion.subject.subject_confirmation print confirmation.keyswv() print confirmation.subject_confirmation_data assert confirmation.subject_confirmation_data.in_response_to == "12" @@ -227,7 +223,7 @@ class TestServer1(): assert not resp.assertion def test_sso_failure_response(self): - exc = utils.MissingValue("eduPersonAffiliation missing") + exc = s_utils.MissingValue("eduPersonAffiliation missing") resp = self.server.error_response( "http://localhost:8087/", "12", "urn:mace:example.com:saml:roland:sp", exc ) @@ -253,10 +249,8 @@ class TestServer1(): resp_str = self.server.authn_response(ava, "1", "http://local:8087/", "urn:mace:example.com:saml:roland:sp", - make_instance(samlp.NameIDPolicy, - utils.args2dict( - format=saml.NAMEID_FORMAT_TRANSIENT, - allow_create="true")), + samlp.NameIDPolicy(format=saml.NAMEID_FORMAT_TRANSIENT, + allow_create="true"), "foba0001@example.com") response = samlp.response_from_string("\n".join(resp_str)) @@ -324,12 +318,12 @@ class TestServer2(): assert response.version == "2.0" assert response.issuer.text == "urn:mace:example.com:saml:roland:idpr" assert response.status.status_code.value == samlp.STATUS_SUCCESS - assert len(response.assertion) == 1 - assertion = response.assertion[0] + assert response.assertion + assertion = response.assertion assert assertion.version == "2.0" subject = assertion.subject assert subject.name_id.format == saml.NAMEID_FORMAT_TRANSIENT - assert len(subject.subject_confirmation) == 1 - subject_confirmation = subject.subject_confirmation[0] + assert subject.subject_confirmation + subject_confirmation = subject.subject_confirmation assert subject_confirmation.subject_confirmation_data.in_response_to == "aaa" diff --git a/tests/test_51_client.py b/tests/test_51_client.py index 1bfa1cf..5444881 100644 --- a/tests/test_51_client.py +++ b/tests/test_51_client.py @@ -2,12 +2,14 @@ # -*- coding: utf-8 -*- import base64 +from urlparse import urlparse, parse_qs from saml2.client import Saml2Client from saml2 import samlp, client, BINDING_HTTP_POST -from saml2 import saml, utils, config, class_name, make_instance +from saml2 import saml, s_utils, config, class_name #from saml2.sigver import correctly_signed_authn_request, verify_signature from saml2.server import Server +from saml2.s_utils import decode_base64_and_inflate import os @@ -27,6 +29,8 @@ def ava(attribute_statement): result[name].append(value.text.strip()) return result +def _leq(l1, l2): + return set(l1) == set(l2) # def test_parse_3(): # xml_response = open(XML_RESPONSE_FILE3).read() @@ -41,7 +45,7 @@ def ava(attribute_statement): # assert False REQ1 = """ -http://vo.example.com/sp1E8042FB4-4D5B-48C3-8E14-8EDD852790DD""" +urn:mace:example.com:saml:roland:spE8042FB4-4D5B-48C3-8E14-8EDD852790DD""" class TestClient: @@ -63,6 +67,7 @@ class TestClient: nameid_format=saml.NAMEID_FORMAT_PERSISTENT) str = "%s" % req.to_string() print str + print REQ1 % req.issue_instant assert str == REQ1 % req.issue_instant assert req.destination == "https://idp.example.com/idp/" assert req.id == "1" @@ -72,7 +77,7 @@ class TestClient: assert name_id.format == saml.NAMEID_FORMAT_PERSISTENT assert name_id.text == "E8042FB4-4D5B-48C3-8E14-8EDD852790DD" issuer = req.issuer - assert issuer.text == "http://vo.example.com/sp1" + assert issuer.text == "urn:mace:example.com:saml:roland:sp" def test_create_attribute_query2(self): req = self.client.create_attribute_query("1", @@ -130,7 +135,7 @@ class TestClient: assert req.id == "1" assert req.version == "2.0" assert req.issue_instant - assert req.issuer.text == "urn:mace:umu.se:saml/rolandsp" + assert req.issuer.text == "urn:mace:example.com:saml:roland:sp" nameid = req.subject.name_id assert nameid.format == saml.NAMEID_FORMAT_TRANSIENT assert nameid.text == "_e7b68a04488f715cda642fbdd90099f5" @@ -146,23 +151,22 @@ class TestClient: assert req == None def test_idp_entry(self): - idp_entry = make_instance( samlp.IDPEntry, - self.client.idp_entry(name="Umeå Universitet", - location="https://idp.umu.se/")) + idp_entry = self.client.idp_entry(name="Umeå Universitet", + location="https://idp.umu.se/") assert idp_entry.name == "Umeå Universitet" assert idp_entry.loc == "https://idp.umu.se/" def test_scope(self): - scope = make_instance(samlp.Scoping, self.client.scoping( - [self.client.idp_entry(name="Umeå Universitet", - location="https://idp.umu.se/")])) + entity_id = "urn:mace:example.com:saml:roland:idp" + locs = self.client.metadata.single_sign_on_services(entity_id) + scope = self.client.scoping_from_metadata(entity_id, locs) assert scope.idp_list assert len(scope.idp_list.idp_entry) == 1 idp_entry = scope.idp_list.idp_entry[0] - assert idp_entry.name == "Umeå Universitet" - assert idp_entry.loc == "https://idp.umu.se/" + assert idp_entry.name == 'Example Co' + assert idp_entry.loc == ['http://localhost:8088/sso/'] def test_create_auth_request_0(self): ar_str = self.client.authn_request("1", @@ -186,7 +190,7 @@ class TestClient: assert self.client.config["virtual_organization"].keys() == [ "urn:mace:example.com:it:tek"] - ar_str = self.client.authn_request("1", + ar_str = self.client.authn_request("666", "http://www.example.com/sso", "http://www.example.org/service", "urn:mace:example.org:saml:sp", @@ -195,6 +199,7 @@ class TestClient: ar = samlp.authn_request_from_string(ar_str) print ar + assert ar.id == "666" assert ar.assertion_consumer_service_url == "http://www.example.org/service" assert ar.destination == "http://www.example.com/sso" assert ar.protocol_binding == BINDING_HTTP_POST @@ -234,17 +239,19 @@ class TestClient: self.client.sec.verify_signature(ar_str, node_name=class_name(ar)) def test_response(self): + IDP = "urn:mace:example.com:saml:roland:idp" + ava = { "givenName": ["Derek"], "surname": ["Jeter"], "mail": ["derek@nyy.mlb.com"]} - resp_str = "\n".join(self.server.authn_response(ava, - "1", "http://local:8087/", - "urn:mace:example.com:saml:roland:sp", - make_instance(samlp.NameIDPolicy, - utils.args2dict( - format=saml.NAMEID_FORMAT_TRANSIENT, - allow_create="true")), - "foba0001@example.com")) + resp_str = "\n".join(self.server.authn_response( + identity=ava, + in_response_to="1", + destination="http://local:8087/", + sp_entity_id="urn:mace:example.com:saml:roland:sp", + name_id_policy=samlp.NameIDPolicy( + format=saml.NAMEID_FORMAT_PERSISTENT), + userid="foba0001@example.com")) resp_str = base64.encodestring(resp_str) @@ -253,7 +260,106 @@ class TestClient: {"1":"http://foo.example.com/service"}) assert authn_response != None + assert authn_response.issuer() == IDP + assert authn_response.response.assertion[0].issuer.text == IDP session_info = authn_response.session_info() - assert session_info["ava"] != [] + + print session_info + assert session_info["ava"] == {'mail': ['derek@nyy.mlb.com'], 'givenName': ['Derek'], 'sn': ['Jeter']} + assert session_info["issuer"] == IDP + assert session_info["came_from"] == "http://foo.example.com/service" response = samlp.response_from_string(authn_response.xmlstr) assert response.destination == "http://local:8087/" + + # One person in the cache + assert len(self.client.users.subjects()) == 1 + subject_id = self.client.users.subjects()[0] + print "||||", self.client.users.get_info_from(subject_id, IDP) + # The information I have about the subject comes from one source + assert self.client.users.issuers_of_info(subject_id) == [IDP] + + # --- authenticate another person + + ava = { "givenName": ["Alfonson"], "surname": ["Soriano"], + "mail": ["alfonson@chc.mlb.com"]} + + resp_str = "\n".join(self.server.authn_response( + identity=ava, + in_response_to="2", + destination="http://local:8087/", + sp_entity_id="urn:mace:example.com:saml:roland:sp", + name_id_policy=samlp.NameIDPolicy( + format=saml.NAMEID_FORMAT_PERSISTENT), + userid="also0001@example.com")) + + resp_str = base64.encodestring(resp_str) + + authn_response = self.client.response({"SAMLResponse":resp_str}, + "urn:mace:example.com:saml:roland:sp", + {"2":"http://foo.example.com/service"}) + + # Two persons in the cache + assert len(self.client.users.subjects()) == 2 + issuers = [self.client.users.issuers_of_info(s) for s in self.client.users.subjects()] + # The information I have about the subjects comes from the same source + print issuers + assert issuers == [[IDP], [IDP]] + + def test_init_values(self): + print self.client.config["service"]["sp"] + spentityid = self.client._spentityid() + print spentityid + assert spentityid == "urn:mace:example.com:saml:roland:sp" + location = self.client._location() + print location + assert location == 'http://localhost:8088/sso/' + service_url = self.client._service_url() + print service_url + assert service_url == "http://lingon.catalogix.se:8087/" + my_name = self.client._my_name() + print my_name + assert my_name == "urn:mace:example.com:saml:roland:sp" + + def test_authenticate(self): + (sid, response) = self.client.authenticate( + "http://www.example.com/sso", + "http://www.example.org/service", + "urn:mace:example.org:saml:sp", + "My Name", + "http://www.example.com/relay_state") + assert sid != None + assert response[0] == "Location" + o = urlparse(response[1]) + qdict = parse_qs(o.query) + assert _leq(qdict.keys(), ['SAMLRequest', 'RelayState']) + saml_request = decode_base64_and_inflate(qdict["SAMLRequest"][0]) + print saml_request + authnreq = samlp.authn_request_from_string(saml_request) + assert authnreq.id == sid + + def test_authenticate_no_args(self): + (sid, request) = self.client.authenticate(relay_state="http://www.example.com/relay_state") + assert sid != None + assert request[0] == "Location" + o = urlparse(request[1]) + qdict = parse_qs(o.query) + assert _leq(qdict.keys(), ['SAMLRequest', 'RelayState']) + saml_request = decode_base64_and_inflate(qdict["SAMLRequest"][0]) + assert qdict["RelayState"][0] == "http://www.example.com/relay_state" + print saml_request + authnreq = samlp.authn_request_from_string(saml_request) + print authnreq.keyswv() + assert authnreq.id == sid + assert authnreq.destination == "http://localhost:8088/sso/" + assert authnreq.assertion_consumer_service_url == "http://lingon.catalogix.se:8087/" + assert authnreq.provider_name == "urn:mace:example.com:saml:roland:sp" + assert authnreq.protocol_binding == "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" + name_id_policy = authnreq.name_id_policy + assert name_id_policy.allow_create == "true" + assert name_id_policy.format == "urn:oasis:names:tc:SAML:2.0:nameid-format:transient" + issuer = authnreq.issuer + assert issuer.text == "urn:mace:example.com:saml:roland:sp" + + + # def test_logout_request(self): + \ No newline at end of file diff --git a/tools/make_metadata.py b/tools/make_metadata.py index 3737941..222b30e 100755 --- a/tools/make_metadata.py +++ b/tools/make_metadata.py @@ -1,10 +1,12 @@ #!/usr/bin/env python import os import getopt +import xmldsig as ds + from saml2 import utils, md, samlp, BINDING_HTTP_POST, BINDING_HTTP_REDIRECT from saml2 import BINDING_SOAP, class_name, make_instance from saml2.time_util import in_a_while -from saml2.utils import parse_attribute_map, args2dict +from saml2.s_utils import parse_attribute_map, factory from saml2.saml import NAME_FORMAT_URI from saml2.sigver import pre_signature_part, SecurityContext from saml2.attribute_converter import from_local_name, ac_factory @@ -30,156 +32,249 @@ class Usage(Exception): DEFAULTS = { "want_assertions_signed": "true", "authn_requests_signed": "false", + "want_authn_requests_signed": "true", } ORG_ATTR_TRANSL = { - "organization_name": "name", - "organization_display_name": "display_name", - "organization_url": "url", + "organization_name": ("name", md.OrganizationName), + "organization_display_name": ("display_name", md.OrganizationDisplayName), + "organization_url": ("url", md.OrganizationURL) } -PERSON_ATTR_TRANSL = { - "company": "company", - "given_name": "givenname", - "sur_name": "surname", - "email_address": "mail", - "telephone_number": "phone", - "type": "type", -} - -def _localized_name(tup): - if tup[1]: - return args2dict(tup[0],lang=tup[1]) - else: - return tup[0] - -def do_organization_info(conf, desc): - """ """ +def _localized_name(val, klass): try: - corg = conf["organization"] - dorg = desc["organization"] = {} - - for (dkey, ckey) in ORG_ATTR_TRANSL.items(): + (text,lang) = val + return klass(text=text,lang=lang) + except ValueError: + return klass(text=val) + +def do_organization_info(conf): + """ decription of an organization in the configuration is + a dictionary of keys and values, where the values might be tuples. + + "organization": { + "name": ("AB Exempel", "se"), + "display_name": ("AB Exempel", "se"), + "url": "http://www.example.org" + } + """ + try: + corg = conf["organization"] + org = md.Organization() + for dkey, (ckey, klass) in ORG_ATTR_TRANSL.items(): if ckey not in corg: continue if isinstance(corg[ckey], basestring): - dorg[dkey] = [corg[ckey]] - elif isinstance(corg[ckey], tuple): - dorg[dkey] = [_localized_name(corg[ckey])] + setattr(org, dkey, [_localized_name(corg[ckey], klass)]) + elif isinstance(corg[ckey], list): + setattr(org, dkey, [_localized_name(n, klass) for n in corg[ckey]]) else: - dorg[dkey] = [] - for val in corg[ckey]: - if isinstance(val,tuple): - dorg[dkey].append(_localized_name(val)) + setattr(org, dkey, [_localized_name(corg[ckey], klass)]) + return org + except KeyError: + return None + +def do_contact_person_info(conf): + """ + """ + contact_person = md.ContactPerson + cps = [] + try: + for corg in conf["contact_person"]: + cp = md.ContactPerson() + for (key, classpec) in contact_person.c_children.values(): + try: + value = corg[key] + data = [] + if isinstance(classpec, list): + # What if value is not a list ? + if isinstance(value, basestring): + data = [classpec[0](text=value)] + else: + for val in value: + data.append(classpec[0](text=val)) else: - dorg[dkey].append(val) + data = classpec(text=value) + setattr(cp, key, data) + except KeyError: + pass + for (prop, classpec, req) in contact_person.c_attributes.values(): + try: + # should do a check for valid value + setattr(cp, prop, corg[prop]) + except KeyError: + pass + cps.append(cp) except KeyError: pass + return cps -def do_contact_person_info(conf, desc): - if "contact_person" in conf: - desc["contact_person"] = [] - for corg in conf["contact_person"]: - dorg = {} - for (dkey, ckey) in PERSON_ATTR_TRANSL.items(): - try: - dorg[dkey] = corg[ckey] - except: - pass - desc["contact_person"].append(dorg) +def do_key_descriptor(cert): + return md.KeyDescriptor( + key_info=ds.KeyInfo( + x509_data=ds.X509Data( + x509_certificate=ds.X509Certificate(text=cert) + ) + ) + ) + +def do_requested_attribute(attributes, acs, is_required="false"): + lista = [] + for attr in attributes: + attr = from_local_name(acs, attr, NAME_FORMAT_URI) + args = {} + for key in attr.keyswv(): + args[key] = getattr(attr,key) + args["is_required"] = is_required + lista.append(md.RequestedAttribute(**args)) + return lista + +ENDPOINTS = { + "sp": { + "artifact_resolution_service": (md.ArtifactResolutionService, True), + "single_logout_service": (md.SingleLogoutService, False), + "manage_name_id_service": (md.ManageNameIDService, False), + "assertion_consumer_service": (md.AssertionConsumerService, True), + }, + "idp":{ + "artifact_resolution_service": (md.ArtifactResolutionService, True), + "single_logout_service": (md.SingleLogoutService, False), + "manage_name_id_service": (md.ManageNameIDService, False), + + "single_sign_on_service": (md.SingleSignOnService, False), + "name_id_mapping_service": (md.NameIDMappingService, False), -def do_sp_sso_descriptor(sp, cert, acs): - desc = { - "protocol_support_enumeration": samlp.NAMESPACE, - "assertion_consumer_service": { - "binding": BINDING_HTTP_POST , - "location": sp["url"], - "index": 0, - }, - "key_descriptor":{ - "key_info": { - "x509_data": { - "x509_certificate": cert - } - } - }, - } + "assertion_id_request_service": (md.AssertionIDRequestService, False), + }, + "aa":{ + "artifact_resolution_service": (md.ArtifactResolutionService, True), + "single_logout_service": (md.SingleLogoutService, False), + "manage_name_id_service": (md.ManageNameIDService, False), + + "assertion_id_request_service": (md.AssertionIDRequestService, False), + + "attribute_service": (md.AttributeService, False) + }, +} + +DEFAULT_BINDING = { + "assertion_consumer_service": BINDING_HTTP_POST, + "single_sign_on_service": BINDING_HTTP_POST, + "single_logout_service": BINDING_HTTP_POST, + "attribute_service": BINDING_SOAP, + "artifact_resolution_service": BINDING_SOAP +} + +def do_endpoints(conf, endpoints): + service = {} + + for endpoint, (eclass, indexed) in endpoints.items(): + try: + servs = [] + i = 1 + for args in conf[endpoint]: + if isinstance(args, basestring): # Assume it's the location + args = {"location":args, "binding": DEFAULT_BINDING[endpoint]} + if indexed: + args["index"] = "%d" % i + servs.append(factory(eclass, **args)) + i += 1 + service[endpoint] = servs + except KeyError: + pass + return service + +def do_sp_sso_descriptor(sp, acs, cert=None): + spsso = md.SPSSODescriptor() + spsso.protocol_support_enumeration=samlp.NAMESPACE + + if sp["endpoints"]: + for (endpoint, instlist) in do_endpoints(sp["endpoints"], + ENDPOINTS["sp"]).items(): + setattr(spsso, endpoint, instlist) + + if cert: + spsso.key_descriptor=do_key_descriptor(cert) for key in ["want_assertions_signed", "authn_requests_signed"]: try: - desc[key] = "%s" % sp[key] + setattr(spsso, key, "%s" % sp[key]) except KeyError: - desc[key] = DEFAULTS[key] + setattr(spsso, key, DEFAULTS[key]) - requested_attribute = [] + requested_attributes = [] if "required_attributes" in sp: - for attr in sp["required_attributes"]: - reqa = from_local_name(acs, attr, NAME_FORMAT_URI) - reqa["is_required"] = "true" - requested_attribute.append(reqa) + requested_attributes.extend(do_requested_attribute( + sp["required_attributes"], + acs, + is_required="true")) if "optional_attributes" in sp: - for attr in sp["optional_attributes"]: - reqa = from_local_name(acs, attr, NAME_FORMAT_URI) - requested_attribute.append(reqa) + requested_attributes.extend(do_requested_attribute( + sp["optional_attributes"], + acs, + is_required="false")) - if requested_attribute: - desc["attribute_consuming_service"] = { - "requested_attribute": requested_attribute, - "service_name": { - "lang":"en", - "text":sp["name"], - } - } + if requested_attributes: + spsso.attribute_consuming_service = [md.AttributeConsumingService( + requested_attribute=requested_attributes, + service_name= [md.ServiceName(lang="en",text=sp["name"])] + )] + try: + spsso.attribute_consuming_service[0].service_description = [ + md.ServiceDescription(text=sp["description"])] + except KeyError: + pass - if "discovery_service" in sp: - desc["extensions"] = {"extension_elements":[ - { - "tag":"DiscoveryResponse", - "namespace":md.IDPDISC, - "attributes": { - "index":"1", - "binding": md.IDPDISC, - "location":sp["url"] - } - } - ]} + # if "discovery_service" in sp: + # spsso.extensions= {"extension_elements":[ + # { + # "tag":"DiscoveryResponse", + # "namespace":md.IDPDISC, + # "attributes": { + # "index":"1", + # "binding": md.IDPDISC, + # "location":sp["url"] + # } + # } + # ]} - return desc + return spsso -def do_idp_sso_descriptor(idp, cert): - return { - "protocol_support_enumeration": samlp.NAMESPACE, - "want_authn_requests_signed": True, - "single_sign_on_service": { - "binding": BINDING_HTTP_REDIRECT , - "location": idp["url"], - }, - "key_descriptor":{ - "key_info": { - "x509_data": { - "x509_certificate": cert - } - } - }, - } +def do_idp_sso_descriptor(idp, cert=None): + idpsso = md.IDPSSODescriptor() + idpsso.protocol_support_enumeration=samlp.NAMESPACE + + if idp["endpoints"]: + for (endpoint, instlist) in do_endpoints(idp["endpoints"], + ENDPOINTS["idp"]).items(): + setattr(idpsso, endpoint, instlist) + if cert: + idpsso.key_descriptor=do_key_descriptor(cert) + + for key in ["want_authn_requests_signed"]: + try: + setattr(idpsso, key, "%s" % idp[key]) + except KeyError: + setattr(idpsso, key, DEFAULTS[key]) + + return idpsso + def do_aa_descriptor(aa, cert): - return { - "protocol_support_enumeration": samlp.NAMESPACE, - "attribute_service": { - "binding": BINDING_SOAP , - "location": aa["url"], - }, - "key_descriptor":{ - "key_info": { - "x509_data": { - "x509_certificate": cert - } - } - }, - } + aa = md.AttributeAuthorityDescriptor() + aa.protocol_support_enumeration=samlp.NAMESPACE + if idp["endpoints"]: + for (endpoint, instlist) in do_endpoints(aa["endpoints"], + ENDPOINTS["aa"]).items(): + setattr(aasso, endpoint, instlist) + + if cert: + aa.key_descriptor=do_key_descriptor(cert) + + return aa + def entity_descriptor(confd, valid_for): mycert = "".join(open(confd["cert_file"]).readlines()[1:-1]) @@ -193,45 +288,43 @@ def entity_descriptor(confd, valid_for): #else: # backward = {} - ed = { - "entity_id": confd["entityid"], - } + ed = md.EntityDescriptor(entity_id=confd["entityid"]) + if valid_for: - ed["valid_until"] = in_a_while(hours=valid_for) + ed.valid_until = in_a_while(hours=valid_for) - do_organization_info(confd, ed) - do_contact_person_info(confd, ed) + ed.organization = do_organization_info(confd) + ed.contact_person = do_contact_person_info(confd) if "sp" in confd["service"]: # The SP - ed["sp_sso_descriptor"] = do_sp_sso_descriptor(confd["service"]["sp"], - mycert, attrconverters) + ed.sp_sso_descriptor = do_sp_sso_descriptor(confd["service"]["sp"], + attrconverters, mycert) if "idp" in confd["service"]: - ed["idp_sso_descriptor"] = do_idp_sso_descriptor( + ed.idp_sso_descriptor = do_idp_sso_descriptor( confd["service"]["idp"], mycert) if "aa" in confd["service"]: - ed["attribute_authority_descriptor"] = do_aa_descriptor( + ed.attribute_authority_descriptor = do_aa_descriptor( confd["service"]["aa"], mycert) return ed def entities_descriptor(eds, valid_for, name, id, sign, sc): - d = {"entity_descriptor": eds} + entities = md.EntitiesDescriptor(entity_descriptor= eds) if valid_for: - d["valid_until"] = in_a_while(hours=valid_for) + entities.valid_until = in_a_while(hours=valid_for) if name: - d["name"] = name + entities.name = name if id: - d["id"] = id + entities.id = id if sign: - d["signature"] = pre_signature_part(d["id"]) + entities.signature = pre_signature_part(id) - statement = make_instance(md.EntitiesDescriptor, d) if sign: - statement = sc.sign_statement_using_xmlsec("%s" % statement, - class_name(statement)) - return statement + entities = sc.sign_statement_using_xmlsec("%s" % entities, + class_name(entities)) + return entities def main(args):