Esempio n. 1
0
    def getCached(self, canLoad=False, user=None, userPassword=None):
        """ Return the RAM only cached data for this safe. 
        @param canLoad: Indicates what to do if the entry doesn't exist. False: Error out. True: Load the safe then return the obj.  
        """
        self.log.debug("Getting cached copy")
        from psafefe.psafe.errors import EntryNotCached

        # Can't load without the password
        from django.contrib.auth.models import User

        if not isinstance(user, User):
            canLoad = False
            self.log.debug("Can't load due to lack of valid user (%r)" % user)
        if not userPassword:
            canLoad = False
            self.log.debug("Can't load due to lack of valid password for user (%r)" % userPassword)
        try:
            return self.mempsafe
        except MemPSafe.DoesNotExist, e:
            if canLoad:
                self.log.debug("Going to try loading")
                try:
                    from psafefe.psafe.tasks.load import loadSafe
                    from psafefe.psafe.functions import getDatabasePasswordByUser

                    dbPassword = getDatabasePasswordByUser(user=user, userPassword=userPassword, psafe=self, wait=True)
                    ls = loadSafe.delay(psafe_pk=self.pk, password=dbPassword, force=False)  # @UndefinedVariable
                    ls.wait()
                    # Make sure to prevent inf. recursion if the load fails
                    return self.getCached(canLoad=False)
                except Exception, e:
                    raise EntryNotCached, "%r doesn't have a cached entry and loading failed with %r" % (self, e)
Esempio n. 2
0
 def test_loadSafe_simple(self):
     import os, sys, os.path
     from django.conf import settings
     from psafefe.psafe.models import *
     testSafeRepo = self.groupsByRepo['testsafes']['repo']
     testSafes = os.listdir(testSafeRepo.path)
     # Ignore non-psafe3 files
     testSafes = filter(lambda fil: fil.endswith('.psafe3'), testSafes)
     
     # Load all safes in the test_safes dir/repo
     from psafefe.psafe.tasks.load import loadSafe
     for safe in testSafes:
         filePath = os.path.join(testSafeRepo.path, safe)
         try:
             psafeObj = PasswordSafe.objects.get(
                                                 filename = filePath,
                                                 repo = testSafeRepo,
                                                 )
         except PasswordSafe.DoesNotExist: 
             psafeObj = PasswordSafe(
                                     filename = filePath,
                                     repo = testSafeRepo,
                                     )
             psafeObj.save()
             
         res = loadSafe.delay(# @UndefinedVariable
                        psafe_pk = psafeObj.pk,
                        password = '******',
                        force = False,
                        )
         self.assertTrue(res, "Failed to load safe %r" % safe)
         
         res = loadSafe.delay(# @UndefinedVariable
                        psafe_pk = psafeObj.pk,
                        password = '******',
                        force = False,
                        )
         self.assertFalse(res, "Loaded safe %r when we shouldn't have" % safe)
         
         res = loadSafe.delay(# @UndefinedVariable
                        psafe_pk = psafeObj.pk,
                        password = '******',
                        force = True,
                        )
         self.assertTrue(res, "Failed forcibly reload safe %r" % safe)
Esempio n. 3
0
def updatePSafeCacheByPSafesPK(username, password, entPKsUnsafe, sync, **kw):
    """ Update the psafe cache for the given entities. If sync is true, 
    then wait for the cache to update before returning. 
    @note: Any safes that the user doesn't have a valid password for will be skipped.
    @note: Any PKs to which a safe doesn't exist or the user lacks at least read-only perms will raise an EntryDoesntExistError.
    
    @warning: If sync is not set the count of successes will NOT include any errors that occur during sync. It will only include ones where the safe password lookup and object lookup succeeded.     
    @param username: Requesting user's login
    @type username: string
    @param password: Requesting user's login
    @type password: string
    @param entPKs: A list of safe PKs that should have their cache updated.
    @type entPKs: list of ints
    @param sync: If True, wait for the safes to be updated before returning. 
    @type sync: boolean
    @return: If sync=False, the number of safes that have had a sync job successfully submitted. If sync=True, then the number of safes that had a sync job submitted andsuccessfullyy completed.  
    @raise NoPermissionError: User doesn't have password safe sync permissions
    """
    # Validate all safes and the users perms to them first
    ents = []
    for pk in list(entPKsUnsafe):
        try:
            ent = PasswordSafe.objects.get(pk = pk)
            ents.append(ent)
        except PasswordSafe.DoesNotExist:
            raise EntryDoesntExistError, "Couldn't find a PasswordSafe where pk=%r" % pk
        if not ent.repo.user_can_access(user = kw['user'], mode = "R"):
            raise EntryDoesntExistError, "Couldn't find a PasswordSafe where pk=%r" % pk
    sync = bool(sync)
    
    if kw['user'].has_perm('psafe.can_sync_passwordsafe'):
        # user has perms
        waits = []
        successes = 0
        for psafe in ents:
            try:
                psafepass = getDatabasePasswordByUser(kw['user'], password, psafe)
                waits.append(loadSafe.delay(psafe_pk = entPK, password = psafepass))  # @UndefinedVariable
                successes += 1
            except:
                # TODO: Add some sort of logging for this
                pass
        # Doing sync, wait for all results
        if sync:
            for i in waits:
                try:
                    i.wait()
                except:
                    # TODO: Add some sort of logging for this
                    successes -= 1
        return successes
    raise NoPermissionError, "User can't sync psafes"
Esempio n. 4
0
def updatePSafeCacheByPSafesByUUID(username, password, entUUIDsUnsafe, sync, **kw):
    """ Update the psafe cache for the given entities. If sync is true, 
    then wait for the cache to update before returning. 
    @note: Any safes that the user doesn't have a valid password for will be skipped. 
    @note: If the user lacks perms to any psafe an EntryDoesntExistError will be raised
    @note: If one of the UUIDs doesn't exist, then an EntryDoesntExistError will be raised.
    @note: If the user has perms to multiple psafes with the same UUID and that UUID is listed, a MultipleEntriesExistError will be raised
    @warning: If sync is not set the count of successes will NOT include any errors that occur during sync. It will only include ones where the safe password lookup and object lookup succeeded.     
    @param username: Requesting user's login
    @type username: string
    @param password: Requesting user's login
    @type password: string
    @param entUUIDs: A list of safe UUIDs that should have their cache updated.
    @type entUUIDs: list of strings
    @param sync: If True, wait for the safes to be updated before returning. 
    @type sync: boolean
    @return: The number of safes successfully updated
    @raise NoPermissionError: User doesn't have password safe sync permissions
    @raise EntryDoesntExistError: No psafe with the request UUID exists that the user as atleast read-only access to. 
    @raise MultipleEntriesExistError: More than one psafe with the given UUID was found. 
    """    
    # Validate input type    
    entUUIDs = []
    for pk in list(entUUIDsUnsafe):
        entUUIDs.append(str(pk))
    sync = bool(sync)

    if kw['user'].has_perm('psafe.can_sync_passwordsafe'):
        # user has perms
        # Validate all safes BEFORE we start calling loadSafe
        validSafes = []
        for entUUID in entUUIDs:
            psafes = PasswordSafe.objects.filter(uuid = entUUID)
            # Validate perms
            okPSafes = []
            for ent in psafes:
                if ent.repo.user_can_access(user = kw['user'], mode = "R"):
                    okPSafes.append(ent) 
            # Only allow one UUID
            if len(psafes) > 1:
                raise MultipleEntriesExistError, "%r safes with a UUID of %r were found" % (psafes.count(), entUUID)
            elif len(psafes) == 0:
                raise EntryDoesntExistError, "Couldn't find a PasswordSafe where uuid=%r" % entUUID
            validSafes.append(psafes[0])
        # All safes found are valid, so start the loadSafes
        waits = []
        successes = 0
        for psafe in validSafes:
            try:
                psafepass = getDatabasePasswordByUser(kw['user'], password, psafe)
                waits.append(loadSafe.delay(psafe_pk = entPK, password = psafepass))  # @UndefinedVariable
                successes += 1
            except:
                # TODO: Add some sort of logging for this
                pass
        # Doing sync, wait for all results and watch for errors
        if sync:
            for i in waits:
                try:
                    i.wait()
                except:
                    # TODO: Add some sort of logging for this
                    successes -= 1
        return successes
    else:
        raise NoPermissionError, "User can't sync psafes"