Exemplo n.º 1
0
    def match(self, query):
        # type: (ICredentialRequirement) -> ICredentialInfo
        """
        Returns a single match from the store

        Args:
            query (ICredentialRequirement):

        Returns:
            ICredentialInfo: A single credential object. If more than one is found, the first is returned
        """

        try:
            assert isinstance(query,
                              ICredentialRequirement), "Error checking 'query'"
        except AssertionError as err:
            raise CredentialsError(
                "Requirements for matching a Credential are wrong. Please check your arguments. %s"
                % err)

        matches = self.matches(query)
        if len(matches) == 1:
            return matches[0]
        if len(matches) > 1:
            logger.debug('More than one match...')
            # If we have a specific object and a general one. Then we ask for a general one, what should we do.
            # Does it matter since they've only asked for a general proxy? What are the use cases?
            return matches[
                0]  # TODO For now just return the first one... Though perhaps we should merge them or something?
        return None
Exemplo n.º 2
0
    def create(self, query, create=True, check_file=False):
        # type: (ICredentialRequirement, bool, bool) -> ICredentialInfo
        """
        Create an ``ICredentialInfo`` for the query.

        Args:
            query (ICredentialRequirement):
            check_file (bool): Raise an exception if the file does not exist
            create (bool): Create the credential file

        Returns:
            The newly created ICredentialInfo object
        """

        try:
            assert isinstance(query,
                              ICredentialRequirement), "Error checking 'query'"
            assert isinstance(create, bool), "Error checking 'create'"
            assert isinstance(check_file, bool), "Error checking 'check_file'"
        except AssertionError as err:
            raise CredentialsError(
                "Requirements to make a Credential are wrong. Please check your arguments. %s"
                % err)

        cred = query.info_class(query, check_file=check_file, create=create)
        self.credentials.add(cred)
        return cred
Exemplo n.º 3
0
    def get(self, query, default=None):
        # type: (ICredentialRequirement, Optional[ICredentialInfo]) -> Optional[ICredentialInfo]
        """
        Return the value for ``query`` if ``query`` is in the store, else default.
        If ``default`` is not given, it defaults to ``None``, so that this method never raises a ``KeyError``.

        Args:
            query (ICredentialRequirement):
            default (ICredentialInfo):

        Returns:
            A single ICredentialInfo object which matches the requirements or ``default``
        """

        try:
            assert isinstance(query,
                              ICredentialRequirement), "Error checking 'query'"
            if default is not None:
                assert isinstance(default,
                                  ICredentialInfo), "Error checking 'default'"
        except AssertionError as err:
            raise CredentialsError(
                "Requirements for get-ing a Credential are wrong. Please check your arguments. %s"
                % err)

        try:
            return self[query]
        except KeyError:
            return default
Exemplo n.º 4
0
    def __init__(self, requirements, check_file=False, create=False):
        # type: (ICredentialRequirement, bool, bool) -> None
        """
        Args:
            requirements (ICredentialRequirement): An object specifying the requirements
            check_file (bool): Raise an exception if the file does not exist
            create (bool): Create the credential file

        Raises:
            IOError: If told to wrap a non-existent file
            CredentialsError: If this object cannot satisfy ``requirements``
        """
        super(ICredentialInfo, self).__init__()

        self.cache = {'mtime': 0}

        self.initial_requirements = copy.deepcopy(
            requirements
        )  # Store the requirements that the object was created with. Used for creation

        if check_file:
            logger.debug('Trying to wrap %s', self.location)
            if not self.exists():
                raise IOError(
                    'Proxy file {path} not found'.format(path=self.location))
            logger.debug('Wrapping existing file %s', self.location)

        if create:
            logger.debug('Making a new one')
            self.create()

        # If the proxy object does not satisfy the requirements then abort the construction
        if not self.check_requirements(requirements):
            raise CredentialsError(
                'Proxy object cannot satisfy its own requirements')
Exemplo n.º 5
0
    def cred_wrapped_method(self, *args, **kwargs):
        cred_req = self.credential_requirements

        try:
            cred = credential_store[cred_req]
        except KeyError:
            if isinstance(threading.current_thread(), threading._MainThread
                          ):  # threading.main_thread() in Python 3.4
                logger.warning('Required credential [%s] not found in store',
                               cred_req)
                cred = credential_store.create(cred_req, create=True)
            else:
                raise CredentialsError(
                    'Cannot get proxy which matches requirements {0}'.format(
                        cred_req))

        if not cred.is_valid():
            if isinstance(threading.current_thread(), threading._MainThread
                          ):  # threading.main_thread() in Python 3.4
                logger.info(
                    'Found credential [%s] but it is invalid. Trying to renew...',
                    cred)
                cred.renew()
            else:
                raise InvalidCredentialError('Proxy is invalid')

        return method(self, *args, **kwargs)
Exemplo n.º 6
0
    def matches(self, query):
        # type: (ICredentialRequirement) -> Sequence[ICredentialInfo]
        """
        Search the credentials in the store for all matches. They must match every condition exactly.

        Args:
            query (ICredentialRequirement):

        Returns:
            list[ICredentialInfo]: An list of all matching objects
        """

        try:
            assert isinstance(query,
                              ICredentialRequirement), "Error checking 'query'"
        except AssertionError as err:
            raise CredentialsError(
                "Requirements for matching any Credential are wrong. Please check your arguments. %s"
                % err)

        return [
            cred for cred in self.get_all_matching_type(query)
            if cred.check_requirements(query)
        ]
Exemplo n.º 7
0
    def get_all_matching_type(self, query):
        # type: (ICredentialRequirement) -> Sequence[ICredentialInfo]
        """
        Returns all ``ICredentialInfo`` with the type that matches the query

        Args:
            query (ICredentialRequirement):

        Returns:
            list[ICredentialInfo]: An list of all matching objects
        """

        try:
            assert isinstance(query,
                              ICredentialRequirement), "Error checking 'query'"
        except AssertionError as err:
            raise CredentialsError(
                "Requirements for matching all Credential are wrong. Please check your arguments. %s"
                % err)

        return [
            cred for cred in self.credentials
            if isinstance(cred, query.info_class)
        ]