예제 #1
0
    def __delitem__(self, key):
        '''
        remove an item from the config

        :param key: the name of the ocnfig entry
        :type  key: string

        :return : return the std value like the std dict does, whatever this is
        :rtype  : any value a dict update will return
        '''
        Key = key

        if self.parent.has_key(key):
            Key = key

        elif self.parent.has_key('linotp.' + key):
            Key = 'linotp.' + key

        res = self.parent.__delitem__(Key)

        # sync with global dict

        self.glo.delConfig(Key)

        # sync with db
        if key.startswith('linotp.'):
            Key = key
        else:
            Key = 'linotp.' + key

        _removeConfigDB(Key)
        _storeConfigDB('linotp.Config', datetime.now())

        return res
예제 #2
0
    def test_storeConfigDB_encoding(self):
        # Test round trip of _storeConfigDB with entries that require
        # encoding of special characters
        conf = {
            "Key": "linotp.TËST",
            "Value": "VALUEÄ",
            "Type": "TYPEß",
            "Description": "DESCRIPTIÖN",
        }

        _storeConfigDB(conf["Key"], conf["Value"], conf["Type"],
                       conf["Description"])

        # Check value is correctly returned
        stored_value = _retrieveConfigDB(conf["Key"])
        assert conf["Value"] == stored_value

        # Check type, description in database
        entries = Config.query.all()

        assert len(entries) == 1
        stored_conf = entries[0]

        for key in list(conf.keys()):
            assert conf[key] == getattr(
                stored_conf,
                key), "Key should match key:%s - expected %r, recevied %r" % (
                    key,
                    conf[key],
                    getattr(stored_conf, key),
                )
예제 #3
0
파일: migrate.py 프로젝트: wjbailey/LinOTP
    def set_config_entry(self, config_entry):
        """
        set the config entry - using the standard way, so that the new value
        will be encrypted using the new encryption key and potetialy as well an
        new iv.

        before storing the new entry, the old value in its encryted form is
        read. The


        :param config_entry: the config entry, as a dict
        :return: - nothing -
        """

        key = config_entry['Key']
        typ = config_entry['Type']
        desc = config_entry['Description']
        if desc == 'None':
            desc = None

        config_entries = Session.query(model_config).\
                         filter(model_config.Key == key).all()
        entry = config_entries[0]

        # decypt the real value
        enc_value = config_entry['Value']
        value = self.crypter.decrypt(enc_value,
                                     just_mac='enc%s' % key + entry.Value)

        _storeConfigDB(key, value, typ=typ, desc=desc)
예제 #4
0
    def test__storeConfigDB_int(self, mock_session):
        """
        test for storing int values
        """

        key = 'linotp.test_data'
        val = 1313123131231231313213
        typ = 'int'
        desc = 'long int'

        continous_entries = ContEntries()

        mock_session.query.return_value.filter.return_value = continous_entries
        _storeConfigDB(key, val, typ=typ, desc=desc)

        # check that the value is realy stored

        conf_keys = list(TestConfigEntries.keys())

        assert key in conf_keys, TestConfigEntries

        assert len(TestConfigEntries) == 1

        entry = TestConfigEntries['linotp.test_data']
        assert entry['value'] == val

        # --------------------------------------------------------------------

        # cleanup the shared dictionary

        for key in list(TestConfigEntries.keys()):
            del TestConfigEntries[key]

        return
예제 #5
0
    def test_storeConfigDB_encoding(self):
        # Test round trip of _storeConfigDB with entries that require
        # encoding of special characters
        conf = {
            'Key': 'linotp.TËST',
            'Value': 'VALUEÄ',
            'Type': 'TYPEß',
            'Description': 'DESCRIPTIÖN',
        }

        _storeConfigDB(conf['Key'], conf['Value'], conf['Type'],
                       conf['Description'])

        # Check value is correctly returned
        stored_value = _retrieveConfigDB(conf['Key'])
        assert conf['Value'] == stored_value

        # Check type, description in database
        entries = Session.query(Config).all()

        assert (len(entries) == 1)
        stored_conf = entries[0]

        for key in list(conf.keys()):
            assert conf[key] == getattr(stored_conf, key), \
                             "Key should match key:%s - expected %r, recevied %r" % (key, conf[key], getattr(stored_conf, key))
예제 #6
0
    def set_config_entry(self, config_entry):
        """
        set the config entry - using the standard way, so that the new value
        will be encrypted using the new encryption key and potetialy as well an
        new iv.

        before storing the new entry, the old value in its encryted form is
        read. The


        :param config_entry: the config entry, as a dict
        :return: - nothing -
        """

        key = config_entry['Key']
        typ = config_entry['Type']
        desc = config_entry['Description']
        if desc == 'None':
            desc = None

        config_entries = Session.query(model_config).\
                         filter(model_config.Key == key).all()
        entry = config_entries[0]

        # decypt the real value
        enc_value = config_entry['Value']
        value = self.crypter.decrypt(enc_value,
                                     just_mac='enc%s' % key + entry.Value)

        _storeConfigDB(key, value, typ=typ, desc=desc)
예제 #7
0
    def test__storeConfigDB_text(self, mock_session):
        """
        test for storing long text entries
        """

        key = 'linotp.test_data'
        val = big_value
        typ = 'text'
        desc = None

        continous_entries = ContEntries()

        mock_session.query.return_value.filter.return_value = continous_entries
        _storeConfigDB(key, val, typ=typ, desc=desc)

        conf_keys = TestConfigEntries.keys()

        self.assertTrue(key in conf_keys, TestConfigEntries)

        entry = TestConfigEntries[key]
        _from_, to_ = entry['desc'].split(':')

        # we count from 0 to eg 3 so we have 4 entries
        self.assertTrue(len(conf_keys) == int(to_) + 1, conf_keys)

        # --------------------------------------------------------------------

        # cleanup the shared dictionary

        for key in TestConfigEntries.keys():
            del TestConfigEntries[key]

        return
예제 #8
0
    def refreshConfig(self, do_reload=False):

        conf = self.glo.getConfig()

        if do_reload is True:
            # in case there is no entry in the dbconf or
            # the config file is newer, we write the config back to the db
            entries = list(conf.keys())
            for entry in entries:
                del conf[entry]

            writeback = False
            # get all conf entries from the config file
            fileconf = current_app.config

            # get all configs from the DB
            (dbconf, delay) = _retrieveAllConfigDB()
            self.glo.setConfigIncomplete(not delay)

            # we only merge the config file once as a removed entry
            #  might reappear otherwise
            if 'linotp.Config' not in dbconf:
                conf.update(fileconf)
                writeback = True

            conf.update(dbconf)
            if writeback is True:
                for con in conf:
                    _storeConfigDB(con, conf.get(con))
                _storeConfigDB('linotp.Config', datetime.now())

            self.glo.setConfig(conf, replace=True)

        super().update(conf)
        return
예제 #9
0
    def __delitem__(self, key):
        '''
        remove an item from the config

        :param key: the name of the ocnfig entry
        :type  key: string

        :return : return the std value like the std dict does, whatever this is
        :rtype  : any value a dict update will return
        '''
        Key = key

        if 'linotp.' + key in self:
            Key = 'linotp.' + key

        elif key in self:
            Key = key

        res = super().__delitem__(Key)

        # sync with global dict

        self.glo.delConfig(Key)

        # sync with db
        if key.startswith('linotp.'):
            Key = key
        else:
            Key = 'linotp.' + key

        _removeConfigDB(Key)
        _storeConfigDB('linotp.Config', datetime.now())

        return res
예제 #10
0
파일: migrate.py 프로젝트: soitun/LinOTP
    def set_config_entry(self, config_entry):
        """
        set the config entry - using the standard way, so that the new value
        will be encrypted using the new encryption key and potetialy as well an
        new iv.

        before storing the new entry, the old value in its encryted form is
        read. The


        :param config_entry: the config entry, as a dict
        :return: - nothing -
        """

        key = config_entry["Key"]
        typ = config_entry["Type"]
        desc = config_entry["Description"]
        if desc == "None":
            desc = None

        config_entries = model_config.query.filter_by(Key=key).all()
        entry = config_entries[0]

        # decypt the real value
        enc_value = config_entry["Value"]
        value = self.crypter.decrypt(enc_value,
                                     just_mac="enc%s" % key + entry.Value)

        _storeConfigDB(key, value, typ=typ, desc=desc)
예제 #11
0
    def test_updateExisting(self):
        # Test the following conditions:
        # - An entry is created with chunklength > 1
        # - The type and description are not set
        # - The entry is reduced to one chunk
        # Verify that the resulting config entry has
        # correctly set the type and description

        key = 'linotp.testupdate'
        longvalue = '*' * 2000
        value = 'value'
        typ = None
        description = None

        _storeConfigDB(key, longvalue, typ, description)
        self.assertEqual(Session.query(Config).count(), 2)
        oldentries = Session.query(Config).all()
        self.assertEqual(len(oldentries), 2)

        _storeConfigDB(key, value, typ, description)
        entries = Session.query(Config).all()
        self.assertEqual(len(entries), 1)

        entry = entries[0]
        self.assertEqual(entry.Key, key)
        self.assertEqual(entry.Value, value)
        self.assertEqual(entry.Description, '')  # None is converted to ''
        self.assertEqual(entry.Type, typ)
예제 #12
0
    def test_updateExisting(self):
        # Test the following conditions:
        # - An entry is created with chunklength > 1
        # - The type and description are not set
        # - The entry is reduced to one chunk
        # Verify that the resulting config entry has
        # correctly set the type and description

        key = 'linotp.testupdate'
        longvalue = '*' * 2000
        value = 'value'
        typ = None
        description = None

        _storeConfigDB(key, longvalue, typ, description)
        self.assertEqual(Session.query(Config).count(), 2)
        oldentries = Session.query(Config).all()
        self.assertEqual(len(oldentries), 2)

        _storeConfigDB(key, value, typ, description)
        entries = Session.query(Config).all()
        self.assertEqual(len(entries), 1)

        entry = entries[0]
        self.assertEqual(entry.Key, key)
        self.assertEqual(entry.Value, value)
        self.assertEqual(entry.Description, '')  # None is converted to ''
        self.assertEqual(entry.Type, typ)
예제 #13
0
    def test_storeConfigDB_encoding(self):
        # Test round trip of _storeConfigDB with entries that require
        # encoding of special characters
        conf = {
            'Key': u'linotp.TËST',
            'Value': u'VALUEÄ',
            'Type': u'TYPEß',
            'Description': u'DESCRIPTIÖN',
        }

        _storeConfigDB(conf['Key'], conf['Value'],
                       conf['Type'], conf['Description'])

        # Check value is correctly returned
        stored_value = _retrieveConfigDB(conf['Key'])
        self.assertEqual(conf['Value'], stored_value)

        # Check type, description in database
        entries = Session.query(Config).all()

        assert(len(entries) == 1)
        stored_conf = entries[0]

        for key in conf.keys():
            self.assertEqual(conf[key], getattr(stored_conf, key),
                             "Key should match key:%s - expected %r, recevied %r" % (key, conf[key], getattr(stored_conf, key)))
예제 #14
0
    def test__storeConfigDB_int(self, mock_session):
        """
        test for storing int values
        """

        key = 'linotp.test_data'
        val = 1313123131231231313213
        typ = 'int'
        desc = 'long int'

        continous_entries = ContEntries()

        mock_session.query.return_value.filter.return_value = continous_entries
        _storeConfigDB(key, val, typ=typ, desc=desc)

        # check that the value is realy stored

        conf_keys = TestConfigEntries.keys()

        self.assertTrue(key in conf_keys, TestConfigEntries)

        self.assertTrue(len(TestConfigEntries) == 1)

        entry = TestConfigEntries['linotp.test_data']
        self.assertTrue(entry['value'] == val)

        # --------------------------------------------------------------------

        # cleanup the shared dictionary

        for key in TestConfigEntries.keys():
            del TestConfigEntries[key]

        return
예제 #15
0
    def test_updateExisting(self):
        # Test the following conditions:
        # - An entry is created with chunklength > 1
        # - The type and description are not set
        # - The entry is reduced to one chunk
        # Verify that the resulting config entry has
        # correctly set the type and description

        key = 'linotp.testupdate'
        longvalue = '*' * 2000
        value = 'value'
        typ = None
        description = None

        _storeConfigDB(key, longvalue, typ, description)
        assert Session.query(Config).count() == 2
        oldentries = Session.query(Config).all()
        assert len(oldentries) == 2

        _storeConfigDB(key, value, typ, description)
        entries = Session.query(Config).all()
        assert len(entries) == 1

        entry = entries[0]
        assert entry.Key == key
        assert entry.Value == value
        assert entry.Description == description
        assert entry.Type == typ
예제 #16
0
    def test__storeConfigDB_text(self, mock_session):
        """
        test for storing long text entries
        """

        key = 'linotp.test_data'
        val = big_value
        typ = 'text'
        desc = None

        continous_entries = ContEntries()

        mock_session.query.return_value.filter.return_value = continous_entries
        _storeConfigDB(key, val, typ=typ, desc=desc)

        conf_keys = list(TestConfigEntries.keys())

        assert key in conf_keys, TestConfigEntries

        entry = TestConfigEntries[key]
        _from_, to_ = entry['desc'].split(':')

        # we count from 0 to eg 3 so we have 4 entries
        assert len(conf_keys) == int(to_) + 1, conf_keys

        # --------------------------------------------------------------------

        # cleanup the shared dictionary

        for key in list(TestConfigEntries.keys()):
            del TestConfigEntries[key]

        return
예제 #17
0
    def update(self, dic):
        '''
        update the config dict with multiple items in a dict

        :param dic: dictionary of multiple items
        :type  dic: dict

        :return : return the std value like the std dict does, whatever this is
        :rtype  : any value a dict update will return
        '''

        #
        # first check if all data is type compliant
        #

        for key, val in dic.items():
            self._check_type(key, val)

        #
        # put the data in the parent dictionary
        #

        res = self.parent.update(dic)

        #
        # and sync the data with the global config dict
        #

        self.glo.setConfig(dic)

        #
        # finally sync the entries to the database
        #

        for key in dic:
            if key != 'linotp.Config':
                _storeConfigDB(key, dic.get(key))

        _storeConfigDB('linotp.Config', datetime.now())
        return res
예제 #18
0
    def update(self, dic):
        '''
        update the config dict with multiple items in a dict

        :param dic: dictionary of multiple items
        :type  dic: dict

        :return : return the std value like the std dict does, whatever this is
        :rtype  : any value a dict update will return
        '''

        #
        # first check if all data is type compliant
        #

        for key, val in list(dic.items()):
            self._check_type(key, val)

        #
        # put the data in the parent dictionary
        #

        res = super().update(dic)

        #
        # and sync the data with the global config dict
        #

        self.glo.setConfig(dic)

        #
        # finally sync the entries to the database
        #

        for key in dic:
            if key != 'linotp.Config':
                _storeConfigDB(key, dic.get(key))

        _storeConfigDB('linotp.Config', datetime.now())
        return res
예제 #19
0
    def __setitem__(self, key, val, typ=None, des=None):
        '''
        implemtation of the assignement operator == internal function

        :param key: key of the dict
        :type  key: string
        :param val: any value, which is put in the dict
        :type  val: any type
        :param typ: used in the database to control if the data is encrypted
        :type  typ: None,string,password
        :param des: literal, which describes the data
        :type  des: string
        '''

        # do some simple typing for known config entries
        self._check_type(key, val)

        nVal = expand_here(val)

        # update this config and sync with global dict and db

        res = self.parent.__setitem__(key, nVal)
        self.glo.setConfig({key: nVal})

        # ----------------------------------------------------------------- --

        # finally store the entry in the database and
        # syncronize as well the global timestamp

        now = datetime.now()

        self.glo.setConfig({'linotp.Config': unicode(now)})

        _storeConfigDB(key, val, typ, des)
        _storeConfigDB('linotp.Config', now)

        return res
예제 #20
0
    def __setitem__(self, key, val, typ=None, des=None):
        '''
        implemtation of the assignement operator == internal function

        :param key: key of the dict
        :type  key: string
        :param val: any value, which is put in the dict
        :type  val: any type
        :param typ: used in the database to control if the data is encrypted
        :type  typ: None,string,password
        :param des: literal, which describes the data
        :type  des: string
        '''

        # do some simple typing for known config entries
        self._check_type(key, val)

        nVal = expand_here(val)

        # update this config and sync with global dict and db

        res = super().__setitem__(key, nVal)
        self.glo.setConfig({key: nVal})

        # ----------------------------------------------------------------- --

        # finally store the entry in the database and
        # syncronize as well the global timestamp

        now = datetime.now()

        self.glo.setConfig({'linotp.Config': str(now)})

        _storeConfigDB(key, val, typ, des)
        _storeConfigDB('linotp.Config', now)

        return res
예제 #21
0
    def test__storeConfigDB_password(self, mock_session, mock_encryptPassword):
        """
        test for storing long crypted password entries
        """

        key = "linotp.test_data"
        val = big_value
        typ = "password"
        desc = None

        mock_encryptPassword.return_value = big_value
        continous_entries = ContEntries()

        mock_session.query.return_value.filter.return_value = continous_entries
        _storeConfigDB(key, val, typ=typ, desc=desc)

        # check that the value is realy stored

        conf_keys = list(TestConfigEntries.keys())

        assert key in conf_keys, TestConfigEntries

        entry = TestConfigEntries[key]
        _from_, to_ = entry["desc"].split(":")

        # we count from 0 to eg 3 so we have 4 entries
        assert len(conf_keys) == int(to_) + 1, conf_keys

        # --------------------------------------------------------------------

        # cleanup the shared dictionary

        for key in list(TestConfigEntries.keys()):
            del TestConfigEntries[key]

        return
예제 #22
0
    def refreshConfig(self, do_reload=False):

        conf = self.glo.getConfig()

        if do_reload is True:
            # in case there is no entry in the dbconf or
            # the config file is newer, we write the config back to the db
            entries = conf.keys()
            for entry in entries:
                del conf[entry]

            writeback = False
            # get all conf entries from the config file
            fileconf = _getConfigFromEnv()

            # get all configs from the DB
            (dbconf, delay) = _retrieveAllConfigDB()
            self.glo.setConfigIncomplete(not delay)

            # we only merge the config file once as a removed entry
            #  might reappear otherwise
            if 'linotp.Config' not in dbconf:
                conf.update(fileconf)
                writeback = True

            conf.update(dbconf)
            # check, if there is a selfTest in the DB and delete it
            if 'linotp.selfTest' in dbconf:
                _removeConfigDB('linotp.selfTest')
                _storeConfigDB('linotp.Config', datetime.now())

            # the only thing we take from the fileconf is the selftest
            if 'linotp.selfTest' in fileconf:
                conf['linotp.selfTest'] = 'True'

            if writeback is True:
                for con in conf:
                    if con != 'linotp.selfTest':
                        _storeConfigDB(con, conf.get(con))
                _storeConfigDB(u'linotp.Config', datetime.now())

            self.glo.setConfig(conf, replace=True)

        self.parent.update(conf)
        return
예제 #23
0
    def refreshConfig(self, do_reload=False):

        conf = self.glo.getConfig()

        if do_reload is True:
            # in case there is no entry in the dbconf or
            # the config file is newer, we write the config back to the db
            entries = conf.keys()
            for entry in entries:
                del conf[entry]

            writeback = False
            # get all conf entries from the config file
            fileconf = _getConfigFromEnv()

            # get all configs from the DB
            (dbconf, delay) = _retrieveAllConfigDB()
            self.glo.setConfigIncomplete(not delay)

            # we only merge the config file once as a removed entry
            #  might reappear otherwise
            if 'linotp.Config' not in dbconf:
                conf.update(fileconf)
                writeback = True

            conf.update(dbconf)
            # check, if there is a selfTest in the DB and delete it
            if 'linotp.selfTest' in dbconf:
                _removeConfigDB('linotp.selfTest')
                _storeConfigDB('linotp.Config', datetime.now())

            # the only thing we take from the fileconf is the selftest
            if 'linotp.selfTest' in fileconf:
                conf['linotp.selfTest'] = 'True'

            if writeback is True:
                for con in conf:
                    if con != 'linotp.selfTest':
                        _storeConfigDB(con, conf.get(con))
                _storeConfigDB('linotp.Config', datetime.now())

            self.glo.setConfig(conf, replace=True)

        self.parent.update(conf)
        return