def test_filter_values_req_opt_4():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    rava = attribute_converter.list_to_local(acs, r)
    oava = attribute_converter.list_to_local(acs, o)

    ava = {"sn": ["Hedberg"], "givenName": ["Roland"],
           "eduPersonAffiliation": ["staff"], "uid": ["rohe0002"]}

    ava = assertion.filter_on_demands(ava, rava, oava)
    print(ava)
    assert _eq(sorted(list(ava.keys())), ['givenName', 'sn'])
    assert ava == {'givenName': ['Roland'], 'sn': ['Hedberg']}
def test_filter_on_attributes_with_missing_optional_attribute():
    ava = {"extra": "foo"}
    eptid = to_dict(Attribute(
        friendly_name="eduPersonTargetedID",
        name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
        name_format=NAME_FORMAT_URI), ONTS)
    assert filter_on_attributes(ava, optional=[eptid], acs=ac_factory()) == {}
def test_assertion_2():
    AVA = {'mail': u'*****@*****.**',
           'eduPersonTargetedID': 'http://lingon.ladok.umu'
                                  '.se:8090/idp!http://lingon.ladok.umu'
                                  '.se:8088/sp!95e9ae91dbe62d35198fbbd5e1fb0976',
           'displayName': u'Roland Hedberg',
           'uid': 'http://roland.hedberg.myopenid.com/'}

    ava = Assertion(AVA)

    policy = Policy({
        "default": {
            "lifetime": {"minutes": 240},
            "attribute_restrictions": None,  # means all I have
            "name_form": NAME_FORMAT_URI
        },
    })

    ava = ava.apply_policy("", policy)
    acs = ac_factory(full_path("attributemaps"))
    attribute = from_local(acs, ava, policy.get_name_form(""))

    assert len(attribute) == 4
    names = [attr.name for attr in attribute]
    assert _eq(sorted(list(names)), [
        'urn:oid:0.9.2342.19200300.100.1.1',
        'urn:oid:0.9.2342.19200300.100.1.3',
        'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
        'urn:oid:2.16.840.1.113730.3.1.241'])
def test_filter_on_attributes_with_missing_required_attribute():
    ava = {"extra": "foo"}
    eptid = to_dict(Attribute(
        friendly_name="eduPersonTargetedID",
        name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
        name_format=NAME_FORMAT_URI), ONTS)
    with pytest.raises(MissingValue):
        filter_on_attributes(ava, required=[eptid], acs=ac_factory())
Exemple #5
0
def test_optional_attributes():
    attrconverters = ac_factory("../tests/attributemaps")
    ras = metadata.do_requested_attribute(
        SP["service"]["sp"]["optional_attributes"], attrconverters)
    assert len(ras) == len(SP["service"]["sp"]["optional_attributes"])
    print(ras[0])
    assert ras[0].name == 'urn:oid:2.5.4.12'
    assert ras[0].name_format == NAME_FORMAT_URI
    assert ras[0].is_required == "false"
def test_filter_on_attributes_with_missing_name_format():
    ava = {"eduPersonTargetedID": "*****@*****.**",
           "eduPersonAffiliation": "test",
           "extra": "foo"}
    eptid = to_dict(Attribute(friendly_name="eduPersonTargetedID",
                              name="urn:myown:eptid",
                              name_format=''), ONTS)
    ava = filter_on_attributes(ava, optional=[eptid], acs=ac_factory())
    assert ava['eduPersonTargetedID'] == "*****@*****.**"
def test_optional_attributes():
    attrconverters = ac_factory("../tests/attributemaps")
    ras = metadata.do_requested_attribute(
                                SP["service"]["sp"]["optional_attributes"],
                                attrconverters)
    assert len(ras) == len(SP["service"]["sp"]["optional_attributes"])
    print(ras[0])
    assert ras[0].name == 'urn:oid:2.5.4.12'
    assert ras[0].name_format == NAME_FORMAT_URI
    assert ras[0].is_required == "false"
def test_filter_values_req_4():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"]}

    raises(MissingValue, filter_on_attributes, ava, required, acs=ac_factory())
def test_filter_on_attributes_1():
    a = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                          friendly_name="serialNumber"), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"], "givenName": ["Lars"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["12345"]
def test_filter_on_attributes_2():

    a = to_dict(Attribute(friendly_name="surName",name="urn:oid:2.5.4.4",
                          name_format=NAME_FORMAT_URI), ONTS)
    required = [a]
    ava = {"sn":["kakavas"]}

    ava = filter_on_attributes(ava,required,acs=ac_factory())
    assert list(ava.keys()) == ['sn']
    assert ava["sn"] == ["kakavas"]
def test_filter_values_req_2():
    a1 = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                           friendly_name="serialNumber"), ONTS)
    a2 = to_dict(Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI,
                           friendly_name="surName"), ONTS)

    required = [a1, a2]
    ava = {"serialNumber": ["12345"], "givenName": ["Lars"]}

    raises(MissingValue, filter_on_attributes, ava, required, acs=ac_factory())
def test_filter_values_req_6():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["54321"]
Exemple #13
0
    def load_complex(self, cnf, typ="", metadata_construction=False):
        try:
            self.setattr(typ, "policy", Policy(cnf["policy"]))
        except KeyError:
            pass

        # for srv, spec in cnf["service"].items():
        #     try:
        #         self.setattr(srv, "policy",
        #                      Policy(cnf["service"][srv]["policy"]))
        #     except KeyError:
        #         pass

        try:
            try:
                acs = ac_factory(cnf["attribute_map_dir"])
            except KeyError:
                acs = ac_factory()

            if not acs:
                raise ConfigurationError(
                    "No attribute converters, something is wrong!!")

            _acs = self.getattr("attribute_converters", typ)
            if _acs:
                _acs.extend(acs)
            else:
                self.setattr(typ, "attribute_converters", acs)

        except KeyError:
            pass

        if not metadata_construction:
            try:
                self.setattr(typ, "metadata",
                             self.load_metadata(cnf["metadata"]))
            except KeyError:
                pass
Exemple #14
0
    def load_complex(self, cnf, typ="", metadata_construction=False):
        try:
            self.setattr(typ, "policy", Policy(cnf["policy"]))
        except KeyError:
            pass

        # for srv, spec in cnf["service"].items():
        #     try:
        #         self.setattr(srv, "policy",
        #                      Policy(cnf["service"][srv]["policy"]))
        #     except KeyError:
        #         pass

        try:
            try:
                acs = ac_factory(cnf["attribute_map_dir"])
            except KeyError:
                acs = ac_factory()

            if not acs:
                raise ConfigurationError(
                    "No attribute converters, something is wrong!!")

            _acs = self.getattr("attribute_converters", typ)
            if _acs:
                _acs.extend(acs)
            else:
                self.setattr(typ, "attribute_converters", acs)

        except KeyError:
            pass

        if not metadata_construction:
            try:
                self.setattr(typ, "metadata",
                             self.load_metadata(cnf["metadata"]))
            except KeyError:
                pass
def test_filter_values_req_opt_0():
    r = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)
    o = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="12345")]), ONTS)

    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, [r], [o], acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert _eq(ava["serialNumber"], ["12345", "54321"])
def test_filter_on_attributes_without_friendly_name():
    ava = {"eduPersonTargetedID": "*****@*****.**",
           "eduPersonAffiliation": "test",
           "extra": "foo"}
    eptid = to_dict(
        Attribute(name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
                  name_format=NAME_FORMAT_URI), ONTS)
    ep_affiliation = to_dict(
        Attribute(name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1",
                  name_format=NAME_FORMAT_URI), ONTS)

    restricted_ava = filter_on_attributes(ava, required=[eptid],
                                          optional=[ep_affiliation],
                                          acs=ac_factory())
    assert restricted_ava == {"eduPersonTargetedID": "*****@*****.**",
                              "eduPersonAffiliation": "test"}
Exemple #17
0
    def test(self):
        failures = 0
        friendly_name = "schacHomeOrganization"
        ava_schac = BuilderAVA("urn:oid:1.3.6.1.4.1.25178.1.2.9",
                               friendly_name, saml_map.MAP['identifier'])

        attr = attribute_from_string(ava_schac.ava)
        acs = attribute_converter.ac_factory()

        for ac in acs:
            try:
                res = ac.ava_from(attr)
            except KeyError:
                failures += 1
            else:
                assert res[0] == "schacHomeOrganization"

        assert failures != len(acs)
Exemple #18
0
    def test(self):
        failures = 0
        friendly_name = 'PersonIdentifier'
        ava_eidas = BuilderAVA(saml_map.EIDAS_NATURALPERSON + friendly_name,
                               friendly_name, saml_map.MAP['identifier'])

        attr = attribute_from_string(ava_eidas.ava)
        acs = attribute_converter.ac_factory()

        for ac in acs:
            try:
                res = ac.ava_from(attr)
            except KeyError:
                failures += 1
            else:
                assert res[0] == friendly_name

        assert failures != len(acs)
    def test(self):
        failures = 0
        friendly_name = 'PersonIdentifier'
        ava_eidas = BuilderAVA(
            saml_map.EIDAS_NATURALPERSON + friendly_name,
            friendly_name,
            saml_map.MAP['identifier'])

        attr = attribute_from_string(ava_eidas.ava)
        acs = attribute_converter.ac_factory()

        for ac in acs:
            try:
                res = ac.ava_from(attr)
            except KeyError:
                failures += 1
            else:
                assert res[0] == friendly_name

        assert failures != len(acs)
    def test(self):
        failures = 0
        friendly_name = "schacHomeOrganization"
        ava_schac = BuilderAVA(
            "urn:oid:1.3.6.1.4.1.25178.1.2.9",
            friendly_name,
            saml_map.MAP['identifier'])

        attr = attribute_from_string(ava_schac.ava)
        acs = attribute_converter.ac_factory()

        for ac in acs:
            try:
                res = ac.ava_from(attr)
            except KeyError:
                failures += 1
            else:
                assert res[0] == "schacHomeOrganization"

        assert failures != len(acs)
Exemple #21
0
    def filter(self, ava, sp_entity_id, mdstore, required=None, optional=None):
        """ What attribute and attribute values returns depends on what
        the SP has said it wants in the request or in the metadata file and
        what the IdP/AA wants to release. An assumption is that what the SP
        asks for overrides whatever is in the metadata. But of course the
        IdP never releases anything it doesn't want to.

        :param ava: The information about the subject as a dictionary
        :param sp_entity_id: The entity ID of the SP
        :param mdstore: A Metadata store
        :param required: Attributes that the SP requires in the assertion
        :param optional: Attributes that the SP regards as optional
        :return: A possibly modified AVA
        """

        _ava = None

        if not self.acs:  # acs MUST have a value, fall back to default.
            self.acs = ac_factory()

        _rest = self.get_entity_categories(sp_entity_id, mdstore, required)
        if _rest:
            _ava = filter_attribute_value_assertions(ava.copy(), _rest)
        elif required or optional:
            logger.debug("required: %s, optional: %s", required, optional)
            _ava = filter_on_attributes(
                ava.copy(), required, optional, self.acs,
                self.get_fail_on_missing_requested(sp_entity_id))

        _rest = self.get_attribute_restrictions(sp_entity_id)
        if _rest:
            if _ava is None:
                _ava = ava.copy()
            _ava = filter_attribute_value_assertions(_ava, _rest)
        elif _ava is None:
            _ava = ava.copy()

        if _ava is None:
            return {}
        else:
            return _ava
Exemple #22
0
    def filter(self, ava, sp_entity_id, mdstore, required=None, optional=None):
        """ What attribute and attribute values returns depends on what
        the SP has said it wants in the request or in the metadata file and
        what the IdP/AA wants to release. An assumption is that what the SP
        asks for overrides whatever is in the metadata. But of course the
        IdP never releases anything it doesn't want to.

        :param ava: The information about the subject as a dictionary
        :param sp_entity_id: The entity ID of the SP
        :param mdstore: A Metadata store
        :param required: Attributes that the SP requires in the assertion
        :param optional: Attributes that the SP regards as optional
        :return: A possibly modified AVA
        """

        _ava = None

        if not self.acs:  # acs MUST have a value, fall back to default.
            self.acs = ac_factory()

        _rest = self.get_entity_categories(sp_entity_id, mdstore, required)
        if _rest:
            _ava = filter_attribute_value_assertions(ava.copy(), _rest)
        elif required or optional:
            logger.debug("required: %s, optional: %s", required, optional)
            _ava = filter_on_attributes(
                ava.copy(), required, optional, self.acs,
                self.get_fail_on_missing_requested(sp_entity_id))

        _rest = self.get_attribute_restrictions(sp_entity_id)
        if _rest:
            if _ava is None:
                _ava = ava.copy()
            _ava = filter_attribute_value_assertions(_ava, _rest)
        elif _ava is None:
            _ava = ava.copy()

        if _ava is None:
            return {}
        else:
            return _ava
def test_filter_on_wire_representation_2():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    ava = {"sn": ["Hedberg"], "givenname": ["Roland"],
           "title": ["Master"], "uid": ["rohe0002"]}

    ava = assertion.filter_on_wire_representation(ava, acs, r, o)
    assert _eq(sorted(list(ava.keys())), ["givenname", "sn", "title"])
 def setup_class(self):
     self.acs = attribute_converter.ac_factory(full_path("attributemaps"))
def test_default():
    acs = attribute_converter.ac_factory()
    assert acs
else:
    kwargs = {}

if args.type == "local":
    if args.cert and args.xmlsec:
        crypto = _get_xmlsec_cryptobackend(args.xmlsec)
        sc = SecurityContext(crypto)
        metad = MetaDataFile(args.item,
                             args.item,
                             cert=args.cert,
                             security=sc,
                             **kwargs)
    else:
        metad = MetaDataFile(args.item, args.item, **kwargs)
elif args.type == "external":
    ATTRCONV = ac_factory(args.attrsmap)
    httpc = HTTPBase()
    crypto = _get_xmlsec_cryptobackend(args.xmlsec)
    sc = SecurityContext(crypto)
    metad = MetaDataExtern(ATTRCONV,
                           args.url,
                           sc,
                           cert=args.cert,
                           http=httpc,
                           **kwargs)

if metad:
    try:
        metad.load()
    except:
        raise
Exemple #27
0
 def setup_class(self):
     self.acs = attribute_converter.ac_factory(full_path("attributemaps"))
Exemple #28
0
parser.add_argument('-t', dest='type')
parser.add_argument('-u', dest='url')
parser.add_argument('-c', dest='cert')
parser.add_argument('-a', dest='attrsmap')
parser.add_argument('-o', dest='output')
parser.add_argument('-x', dest='xmlsec')
parser.add_argument(dest="item")
args = parser.parse_args()


metad = None

if args.type == "local":
    metad = MetaDataFile(args.item, args.item)
elif args.type == "external":
    ATTRCONV = ac_factory(args.attrsmap)
    httpc = HTTPBase()
    crypto = _get_xmlsec_cryptobackend(args.xmlsec)
    sc = SecurityContext(crypto)
    metad = MetaDataExtern(ATTRCONV, args.url, sc, cert=args.cert, http=httpc)

if metad is not None:
    metad.load()
    txt = metad.dumps()
    if args.output:
        f = open(args.output, "w")
        f.write(txt)
        f.close()
    else:
        print(txt)
Exemple #29
0
def test_default():
    acs = attribute_converter.ac_factory()
    assert acs
from contextlib import closing
from saml2_tophat import sigver
from saml2_tophat import config
from saml2_tophat.assertion import Policy
from saml2_tophat.attribute_converter import ac_factory
from pathutils import full_path
from saml2_tophat.mdstore import MetadataStore
from saml2_tophat.server import Server


ATTRCONV = ac_factory(full_path("attributemaps"))
sec_config = config.Config()
sec_config.xmlsec_binary = sigver.get_xmlsec_binary(["/opt/local/bin"])

__author__ = 'rolandh'

MDS = MetadataStore(ATTRCONV, sec_config,
                    disable_ssl_certificate_validation=True)
MDS.imp([{"class": "saml2_tophat.mdstore.MetaDataMD",
          "metadata": [(full_path("swamid.md"),)]}])


def _eq(l1, l2):
    return set(l1) == set(l2)


def test_filter_ava():
    policy = Policy({
        "default": {
            "lifetime": {"minutes": 15},
            # "attribute_restrictions": None  # means all I have
Exemple #31
0
#!/usr/bin/env python
import time
from saml2_tophat.attribute_converter import ac_factory
from saml2_tophat.mdstore import MetaDataMD, MetaDataFile

__author__ = 'rolandh'

start = time.time()
for i in range(1, 10):
    mdmd = MetaDataMD(ac_factory("../tests/attributemaps"), "swamid2.md")
    mdmd.load()

    _ = mdmd.keys()

print(time.time() - start)

start = time.time()
for i in range(1, 10):
    mdf = MetaDataFile(ac_factory("../tests/attributemaps"),
                       "../tests/swamid-2.0.xml")
    mdf.load()
    _ = mdf.keys()

print(time.time() - start)