Exemple #1
0
    def set(self, name_id, entity_id, info, not_on_or_after=0):
        """ Stores session information in the cache. Assumes that the name_id
        is unique within the context of the Service Provider.

        :param name_id: The subject identifier, a NameID instance
        :param entity_id: The identifier of the entity_id/receiver of an
            assertion
        :param info: The session info, the assertion is part of this
        :param not_on_or_after: A time after which the assertion is not valid.
        """
        info = dict(info)
        if 'name_id' in info and not isinstance(info['name_id'], six.string_types):
            # make friendly to (JSON) serialization
            info['name_id'] = code(name_id)

        cni = code(name_id)
        if cni not in self._db:
            self._db[cni] = {}

        self._db[cni][entity_id] = (not_on_or_after, info)
        if self._sync:
            try:
                self._db.sync()
            except AttributeError:
                pass
Exemple #2
0
    def entities(self, name_id):
        """ Returns all the entities of assertions for a subject, disregarding
        whether the assertion still is valid or not.

        :param name_id: The subject identifier, a NameID instance
        :return: A possibly empty list of entity identifiers
        """
        cni = code(name_id)
        return list(self._db[cni].keys())
Exemple #3
0
    def _construct_identity(self, session_info):
        cni = code(session_info["name_id"])
        identity = {
            "login": cni,
            "password": "",
            "repoze.who.userid": cni,
            "user": session_info["ava"],
        }
        logger.debug("Identity: %s", identity)

        return identity
Exemple #4
0
    def _construct_identity(self, session_info):
        cni = code(session_info["name_id"])
        identity = {
            "login": cni,
            "password": "",
            "repoze.who.userid": cni,
            "user": session_info["ava"],
        }
        logger.debug("Identity: %s", identity)

        return identity
Exemple #5
0
    def delete(self, name_id):
        """

        :param name_id: The subject identifier, a NameID instance
        """
        del self._db[code(name_id)]

        if self._sync:
            try:
                self._db.sync()
            except AttributeError:
                pass
Exemple #6
0
    def active(self, name_id, entity_id):
        """ Returns the status of assertions from a specific entity_id.

        :param name_id: The ID of the subject
        :param entity_id: The entity ID of the entity_id of the assertion
        :return: True or False depending on if the assertion is still
            valid or not.
        """
        try:
            cni = code(name_id)
            (timestamp, info) = self._db[cni][entity_id]
        except KeyError:
            return False

        if not info:
            return False
        else:
            return time_util.not_on_or_after(timestamp)
Exemple #7
0
    def test_add_person(self):
        session_info = {
            "name_id": nid,
            "issuer": IDP_ONE,
            "not_on_or_after": in_a_while(minutes=15),
            "ava": {
                "givenName": "Anders",
                "surName": "Andersson",
                "mail": "*****@*****.**"
            }
        }
        self.population.add_information_about_person(session_info)

        issuers = self.population.issuers_of_info(nid)
        assert list(issuers) == [IDP_ONE]
        subjects = [code(c) for c in self.population.subjects()]
        assert subjects == [cnid]
        # Are any of the sources gone stale
        stales = self.population.stale_sources_for_person(nid)
        assert stales == []
        # are any of the possible sources not used or gone stale
        possible = [IDP_ONE, IDP_OTHER]
        stales = self.population.stale_sources_for_person(nid, possible)
        assert stales == [IDP_OTHER]

        (identity, stale) = self.population.get_identity(nid)
        assert stale == []
        assert identity == {
            'mail': '*****@*****.**',
            'givenName': 'Anders',
            'surName': 'Andersson'
        }

        info = self.population.get_info_from(nid, IDP_ONE)
        assert sorted(list(info.keys())) == sorted(
            ["not_on_or_after", "name_id", "ava"])
        assert info["name_id"] == nid
        assert info["ava"] == {
            'mail': '*****@*****.**',
            'givenName': 'Anders',
            'surName': 'Andersson'
        }
Exemple #8
0
    def get(self, name_id, entity_id, check_not_on_or_after=True):
        """ Get session information about a subject gotten from a
        specified IdP/AA.

        :param name_id: The subject identifier, a NameID instance
        :param entity_id: The identifier of the entity_id
        :param check_not_on_or_after: if True it will check if this
             subject is still valid or if it is too old. Otherwise it
             will not check this. True by default.
        :return: The session information
        """
        cni = code(name_id)
        (timestamp, info) = self._db[cni][entity_id]
        info = info.copy()
        if check_not_on_or_after and time_util.after(timestamp):
            raise ToOld("past %s" % str(timestamp))

        if 'name_id' in info and isinstance(info['name_id'], six.string_types):
            info['name_id'] = decode(info['name_id'])
        return info or None
    def test_add_another_person(self):
        session_info = {
            "name_id": nida,
            "issuer": IDP_ONE,
            "not_on_or_after": in_a_while(minutes=15),
            "ava": {
                "givenName": "Bertil",
                "surName": "Bertilsson",
                "mail": "*****@*****.**"
            }
        }
        self.population.add_information_about_person(session_info)

        issuers = self.population.issuers_of_info(nida)
        assert list(issuers) == [IDP_ONE]
        subjects = [code(c) for c in self.population.subjects()]
        assert _eq(subjects, [cnid, cnida])

        stales = self.population.stale_sources_for_person(nida)
        assert stales == []
        # are any of the possible sources not used or gone stale
        possible = [IDP_ONE, IDP_OTHER]
        stales = self.population.stale_sources_for_person(nida, possible)
        assert stales == [IDP_OTHER]

        (identity, stale) = self.population.get_identity(nida)
        assert stale == []
        assert identity == {"givenName": "Bertil",
                            "surName": "Bertilsson",
                            "mail": "*****@*****.**"
                            }

        info = self.population.get_info_from(nida, IDP_ONE)
        assert sorted(list(info.keys())) == sorted(["not_on_or_after",
                                                    "name_id", "ava"])
        assert info["name_id"] == nida
        assert info["ava"] == {"givenName": "Bertil",
                                "surName": "Bertilsson",
                                "mail": "*****@*****.**"
                                }
Exemple #10
0
    def get_identity(self, name_id, entities=None,
                     check_not_on_or_after=True):
        """ Get all the identity information that has been received and
        are still valid about the subject.

        :param name_id: The subject identifier, a NameID instance
        :param entities: The identifiers of the entities whoes assertions are
            interesting. If the list is empty all entities are interesting.
        :return: A 2-tuple consisting of the identity information (a
            dictionary of attributes and values) and the list of entities
            whoes information has timed out.
        """
        if not entities:
            try:
                cni = code(name_id)
                entities = self._db[cni].keys()
            except KeyError:
                return {}, []

        res = {}
        oldees = []
        for entity_id in entities:
            try:
                info = self.get(name_id, entity_id, check_not_on_or_after)
            except ToOld:
                oldees.append(entity_id)
                continue

            if not info:
                oldees.append(entity_id)
                continue

            for key, vals in info["ava"].items():
                try:
                    tmp = set(res[key]).union(set(vals))
                    res[key] = list(tmp)
                except KeyError:
                    res[key] = vals
        return res, oldees
    def test_modify_person(self):
        session_info = {
            "name_id": nid,
            "issuer": IDP_ONE,
            "not_on_or_after": in_a_while(minutes=15),
            "ava": {
                "givenName": "Arne",
                "surName": "Andersson",
                "mail": "*****@*****.**"
            }
        }
        self.population.add_information_about_person(session_info)

        issuers = self.population.issuers_of_info(nid)
        assert _eq(issuers, [IDP_ONE, IDP_OTHER])
        subjects = [code(c) for c in self.population.subjects()]
        assert _eq(subjects, [cnid, cnida])
        # Are any of the sources gone stale
        stales = self.population.stale_sources_for_person(nid)
        assert stales == []
        # are any of the possible sources not used or gone stale
        possible = [IDP_ONE, IDP_OTHER]
        stales = self.population.stale_sources_for_person(nid, possible)
        assert stales == []

        (identity, stale) = self.population.get_identity(nid)
        assert stale == []
        assert identity == {'mail': '*****@*****.**',
                            'givenName': 'Arne',
                            'surName': 'Andersson',
                            "eduPersonEntitlement": "Anka"}

        info = self.population.get_info_from(nid, IDP_OTHER)
        assert sorted(list(info.keys())) == sorted(["not_on_or_after",
                                                    "name_id", "ava"])
        assert info["name_id"] == nid
        assert info["ava"] == {"eduPersonEntitlement": "Anka"}
def nid_eq(l1, l2):
    return _eq([code(c) for c in l1], [code(c) for c in l2])
Exemple #13
0
    def do_logout(self, name_id, entity_ids, reason, expire, sign=None,
                  expected_binding=None, sign_alg=None, digest_alg=None,
                  **kwargs):
        """

        :param name_id: Identifier of the Subject (a NameID instance)
        :param entity_ids: List of entity ids for the IdPs that have provided
            information concerning the subject
        :param reason: The reason for doing the logout
        :param expire: Try to logout before this time.
        :param sign: Whether to sign the request or not
        :param expected_binding: Specify the expected binding then not try it
            all
        :param kwargs: Extra key word arguments.
        :return:
        """
        # check time
        if not not_on_or_after(expire):  # I've run out of time
            # Do the local logout anyway
            self.local_logout(name_id)
            return 0, "504 Gateway Timeout", [], []

        not_done = entity_ids[:]
        responses = {}

        for entity_id in entity_ids:
            logger.debug("Logout from '%s'", entity_id)
            # for all where I can use the SOAP binding, do those first
            for binding in [BINDING_SOAP, BINDING_HTTP_POST,
                            BINDING_HTTP_REDIRECT]:
                if expected_binding and binding != expected_binding:
                    continue
                try:
                    srvs = self.metadata.single_logout_service(entity_id,
                                                               binding,
                                                               "idpsso")
                except:
                    srvs = None

                if not srvs:
                    logger.debug("No SLO '%s' service", binding)
                    continue

                destination = destinations(srvs)[0]
                logger.info("destination to provider: %s", destination)
                try:
                    session_info = self.users.get_info_from(name_id,
                                                            entity_id,
                                                            False)
                    session_indexes = [session_info['session_index']]
                except KeyError:
                    session_indexes = None
                req_id, request = self.create_logout_request(
                    destination, entity_id, name_id=name_id, reason=reason,
                    expire=expire, session_indexes=session_indexes)

                # to_sign = []
                if binding.startswith("http://"):
                    sign = True

                if sign is None:
                    sign = self.logout_requests_signed

                sigalg = None
                if sign:
                    if binding == BINDING_HTTP_REDIRECT:
                        sigalg = kwargs.get(
                            "sigalg", ds.DefaultSignature().get_sign_alg())
                        # key = kwargs.get("key", self.signkey)
                        srequest = str(request)
                    else:
                        srequest = self.sign(request, sign_alg=sign_alg,
                                             digest_alg=digest_alg)
                else:
                    srequest = str(request)

                relay_state = self._relay_state(req_id)

                http_info = self.apply_binding(binding, srequest, destination,
                                               relay_state, sign=sign, sigalg=sigalg)

                if binding == BINDING_SOAP:
                    response = self.send(**http_info)

                    if response and response.status_code == 200:
                        not_done.remove(entity_id)
                        response = response.text
                        logger.info("Response: %s", response)
                        res = self.parse_logout_request_response(response,
                                                                 binding)
                        responses[entity_id] = res
                    else:
                        logger.info("NOT OK response from %s", destination)

                else:
                    self.state[req_id] = {"entity_id": entity_id,
                                          "operation": "SLO",
                                          "entity_ids": entity_ids,
                                          "name_id": code(name_id),
                                          "reason": reason,
                                          "not_on_or_after": expire,
                                          "sign": sign}

                    responses[entity_id] = (binding, http_info)
                    not_done.remove(entity_id)

                # only try one binding
                break

        if not_done:
            # upstream should try later
            raise LogoutError("%s" % (entity_ids,))

        return responses
Exemple #14
0
def nid_eq(l1, l2):
    return _eq([code(c) for c in l1], [code(c) for c in l2])
Exemple #15
0
from saml2_tophat.population import Population
from saml2_tophat.time_util import in_a_while

IDP_ONE = "urn:mace:example.com:saml:one:idp"
IDP_OTHER = "urn:mace:example.com:saml:other:idp"

nid = NameID(name_qualifier="foo",
             format=NAMEID_FORMAT_TRANSIENT,
             text="123456")

nida = NameID(name_qualifier="foo",
              format=NAMEID_FORMAT_TRANSIENT,
              text="abcdef")

cnid = code(nid)
cnida = code(nida)


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


class TestPopulationMemoryBased():
    def setup_class(self):
        self.population = Population()

    def test_add_person(self):
        session_info = {
            "name_id": nid,
            "issuer": IDP_ONE,
Exemple #16
0
    def do_logout(self,
                  name_id,
                  entity_ids,
                  reason,
                  expire,
                  sign=None,
                  expected_binding=None,
                  sign_alg=None,
                  digest_alg=None,
                  **kwargs):
        """

        :param name_id: Identifier of the Subject (a NameID instance)
        :param entity_ids: List of entity ids for the IdPs that have provided
            information concerning the subject
        :param reason: The reason for doing the logout
        :param expire: Try to logout before this time.
        :param sign: Whether to sign the request or not
        :param expected_binding: Specify the expected binding then not try it
            all
        :param kwargs: Extra key word arguments.
        :return:
        """
        # check time
        if not not_on_or_after(expire):  # I've run out of time
            # Do the local logout anyway
            self.local_logout(name_id)
            return 0, "504 Gateway Timeout", [], []

        not_done = entity_ids[:]
        responses = {}

        for entity_id in entity_ids:
            logger.debug("Logout from '%s'", entity_id)
            # for all where I can use the SOAP binding, do those first
            for binding in [
                    BINDING_SOAP, BINDING_HTTP_POST, BINDING_HTTP_REDIRECT
            ]:
                if expected_binding and binding != expected_binding:
                    continue
                try:
                    srvs = self.metadata.single_logout_service(
                        entity_id, binding, "idpsso")
                except:
                    srvs = None

                if not srvs:
                    logger.debug("No SLO '%s' service", binding)
                    continue

                destination = destinations(srvs)[0]
                logger.info("destination to provider: %s", destination)
                try:
                    session_info = self.users.get_info_from(
                        name_id, entity_id, False)
                    session_indexes = [session_info['session_index']]
                except KeyError:
                    session_indexes = None
                req_id, request = self.create_logout_request(
                    destination,
                    entity_id,
                    name_id=name_id,
                    reason=reason,
                    expire=expire,
                    session_indexes=session_indexes)

                # to_sign = []
                if binding.startswith("http://"):
                    sign = True

                if sign is None:
                    sign = self.logout_requests_signed

                sigalg = None
                if sign:
                    if binding == BINDING_HTTP_REDIRECT:
                        sigalg = kwargs.get(
                            "sigalg",
                            ds.DefaultSignature().get_sign_alg())
                        # key = kwargs.get("key", self.signkey)
                        srequest = str(request)
                    else:
                        srequest = self.sign(request,
                                             sign_alg=sign_alg,
                                             digest_alg=digest_alg)
                else:
                    srequest = str(request)

                relay_state = self._relay_state(req_id)

                http_info = self.apply_binding(binding,
                                               srequest,
                                               destination,
                                               relay_state,
                                               sign=sign,
                                               sigalg=sigalg)

                if binding == BINDING_SOAP:
                    response = self.send(**http_info)

                    if response and response.status_code == 200:
                        not_done.remove(entity_id)
                        response = response.text
                        logger.info("Response: %s", response)
                        res = self.parse_logout_request_response(
                            response, binding)
                        responses[entity_id] = res
                    else:
                        logger.info("NOT OK response from %s", destination)

                else:
                    self.state[req_id] = {
                        "entity_id": entity_id,
                        "operation": "SLO",
                        "entity_ids": entity_ids,
                        "name_id": code(name_id),
                        "reason": reason,
                        "not_on_or_after": expire,
                        "sign": sign
                    }

                    responses[entity_id] = (binding, http_info)
                    not_done.remove(entity_id)

                # only try one binding
                break

        if not_done:
            # upstream should try later
            raise LogoutError("%s" % (entity_ids, ))

        return responses
from saml2_tophat.ident import code
from saml2_tophat.saml import NAMEID_FORMAT_TRANSIENT, NameID

from saml2_tophat.population import Population
from saml2_tophat.time_util import in_a_while

IDP_ONE = "urn:mace:example.com:saml:one:idp"
IDP_OTHER = "urn:mace:example.com:saml:other:idp"

nid = NameID(name_qualifier="foo", format=NAMEID_FORMAT_TRANSIENT,
             text="123456")

nida = NameID(name_qualifier="foo", format=NAMEID_FORMAT_TRANSIENT,
              text="abcdef")

cnid = code(nid)
cnida = code(nida)

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

class TestPopulationMemoryBased():
    def setup_class(self):
        self.population = Population()

    def test_add_person(self):
        session_info = {
            "name_id": nid,
            "issuer": IDP_ONE,
            "not_on_or_after": in_a_while(minutes=15),
            "ava": {