Exemplo n.º 1
0
 def test_crypt_file_error(self):
     crypt = Crypt()
     with pytest.raises(FileDoesNotExistException) as excinfo:
         crypt.read_key()
     assert ("Decrypt key None not exists. You must set a correct env var KEY_FILE or run "
             "`pyms crypt create-key` command") \
            in str(excinfo.value)
Exemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        """
        Get configuration from a dictionary(variable `config`), from path (variable `path`) or from
        environment with the constant `CONFIGMAP_FILE`
        Set the configuration as upper case to inject the keys in flask config. Flask search for uppercase keys in
        `app.config.from_object`
        ```python
        if key.isupper():
            self[key] = getattr(obj, key)
        ```
        """
        self._loader = LoadFile(kwargs.get("path"), CONFIGMAP_FILE_ENVIRONMENT,
                                DEFAULT_CONFIGMAP_FILENAME)
        self._crypt = Crypt(path=kwargs.get("path"))
        self._empty_init = kwargs.get("empty_init", False)
        config = kwargs.get("config")
        if config is None:
            config = self._loader.get_file(anyconfig.load)
        if not config:
            if self._empty_init:
                config = {}
            else:
                path = self._loader.path if self._loader.path else ""
                raise ConfigDoesNotFoundException(
                    "Configuration file {}not found".format(path + " "))

        config = self.set_config(config)

        super(ConfFile, self).__init__(config)
Exemplo n.º 3
0
 def test_encrypt_conf(self):
     crypt = Crypt(path=self.BASE_DIR)
     crypt._loader.put_file(b"9IXx2F5d5Ob-h5xdCnFSUXhuFKLGRibvLfSbixpcfCw=",
                            "wb")
     config = get_conf(service=CONFIG_BASE, uppercase=True)
     crypt.delete_key()
     assert config.database_url == "http://database-url"
Exemplo n.º 4
0
 def test_generate_file_ok(self, input):
     crypt = Crypt()
     arguments = [
         "create-key",
     ]
     cmd = Command(arguments=arguments, autorun=False)
     cmd.run()
     crypt.delete_key()
Exemplo n.º 5
0
 def test_output_key(self, input):
     crypt = Crypt()
     arguments = [
         "create-key",
     ]
     cmd = Command(arguments=arguments, autorun=False)
     cmd.run()
     with pytest.raises(FileNotFoundError) as excinfo:
         crypt.delete_key()
     assert ("[Errno 2] No such file or directory: 'key.key'") in str(
         excinfo.value)
Exemplo n.º 6
0
 def test_crypt_file_ok(self):
     crypt = Crypt()
     crypt.generate_key("mypassword", True)
     message = "My crypt message"
     encrypt_message = crypt.encrypt(message)
     assert message == crypt.decrypt(str(encrypt_message, encoding="utf-8"))
     crypt.delete_key()
Exemplo n.º 7
0
Arquivo: main.py Projeto: KeoH/pyms
 def run(self):
     crypt = Crypt()
     if self.create_key:
         path = crypt._loader.get_or_setpath()  # pylint: disable=protected-access
         pwd = self.get_input('Type a password to generate the key file: ')
         generate_file = self.get_input(
             'Do you want to generate a file in {}? [Y/n]'.format(path))
         generate_file = generate_file.lower() != "n"
         key = crypt.generate_key(pwd, generate_file)
         if generate_file:
             self.print_ok("File {} generated OK".format(path))
         else:
             self.print_ok("Key generated: {}".format(key))
     if self.encrypt:
         encrypted = crypt.encrypt(self.encrypt)
         self.print_ok("Encrypted OK: {}".format(encrypted))
     return True
Exemplo n.º 8
0
 def test_crypt_file_ok(self):
     crypt = Crypt()
     crypt.generate_key("mypassword", True)
     arguments = ["encrypt", "prueba"]
     cmd = Command(arguments=arguments, autorun=False)
     cmd.run()
     crypt.delete_key()
Exemplo n.º 9
0
 def run(self):
     crypt = Crypt()
     if self.create_key:
         path = crypt._loader.get_path_from_env()  # pylint: disable=protected-access
         pwd = self.get_input('Type a password to generate the key file: ')
         generate_file = self.get_input(
             'Do you want to generate a file in {}? [Y/n]'.format(path))
         generate_file = generate_file.lower() != "n"
         key = crypt.generate_key(pwd, generate_file)
         if generate_file:
             self.print_ok("File {} generated OK".format(path))
         else:
             self.print_ok("Key generated: {}".format(key))
     if self.encrypt:
         encrypted = crypt.encrypt(self.encrypt)
         self.print_ok("Encrypted OK: {}".format(encrypted))
     if self.startproject:
         check_package_exists("cookiecutter")
         cookiecutter = import_from("cookiecutter.main", "cookiecutter")
         cookiecutter('gh:python-microservices/cookiecutter-pyms',
                      checkout=self.branch)
         self.print_ok("Created project OK")
     return True
Exemplo n.º 10
0
class ConfFile(dict):
    """Recursive get configuration from dictionary, a config file in JSON or YAML format from a path or
    `CONFIGMAP_FILE` environment variable.
    **Atributes:**
    * path: Path to find the `DEFAULT_CONFIGMAP_FILENAME` and `DEFAULT_KEY_FILENAME` if use encrypted vars
    * empty_init: Allow blank variables
    * config: Allow to pass a dictionary to ConfFile without use a file
    """
    _empty_init = False

    def __init__(self, *args, **kwargs):
        """
        Get configuration from a dictionary(variable `config`), from path (variable `path`) or from
        environment with the constant `CONFIGMAP_FILE`
        Set the configuration as upper case to inject the keys in flask config. Flask search for uppercase keys in
        `app.config.from_object`
        ```python
        if key.isupper():
            self[key] = getattr(obj, key)
        ```
        """
        self._loader = LoadFile(kwargs.get("path"), CONFIGMAP_FILE_ENVIRONMENT,
                                DEFAULT_CONFIGMAP_FILENAME)
        self._crypt = Crypt(path=kwargs.get("path"))
        self._empty_init = kwargs.get("empty_init", False)
        config = kwargs.get("config")
        if config is None:
            config = self._loader.get_file(anyconfig.load)
        if not config:
            if self._empty_init:
                config = {}
            else:
                path = self._loader.path if self._loader.path else ""
                raise ConfigDoesNotFoundException(
                    "Configuration file {}not found".format(path + " "))

        config = self.set_config(config)

        super(ConfFile, self).__init__(config)

    def to_flask(self) -> Dict:
        return ConfFile(config={k.upper(): v for k, v in self.items()})

    def set_config(self, config: Dict) -> Dict:
        """
        Set a dictionary as attributes of ConfFile. This attributes could be access as `ConfFile["attr"]` or
        ConfFile.attr
        :param config: a dictionary from `config.yml`
        :return:
        """
        config = dict(self.normalize_config(config))
        pop_encripted_keys = []
        for k, v in config.items():
            if k.lower().startswith("enc_"):
                k_not_crypt = re.compile(re.escape('enc_'), re.IGNORECASE)
                setattr(self, k_not_crypt.sub('', k), self._crypt.decrypt(v))
                pop_encripted_keys.append(k)
            else:
                setattr(self, k, v)

        # Delete encrypted keys to prevent decrypt multiple times a element
        for x in pop_encripted_keys:
            config.pop(x)

        return config

    def normalize_config(
            self,
            config: Dict) -> Iterable[Tuple[Text, Union[Dict, Text, bool]]]:
        for key, item in config.items():
            if isinstance(item, dict):
                item = ConfFile(config=item, empty_init=self._empty_init)
            yield self.normalize_keys(key), item

    @staticmethod
    def normalize_keys(key: Text) -> Text:
        """The keys will be transformed to a attribute. We need to replace the charactes not valid"""
        key = key.replace("-", "_")
        return key

    def __eq__(self, other):
        if not isinstance(other, ConfFile) and not isinstance(other, dict):
            return False
        return dict(self) == dict(other)

    def __getattr__(self, name, *args, **kwargs):
        try:
            keys = self.normalize_keys(name).split(".")
            aux_dict = self
            for k in keys:
                aux_dict = aux_dict[k]
            return aux_dict
        except KeyError:
            if self._empty_init:
                return ConfFile(config={}, empty_init=self._empty_init)
            raise AttrDoesNotExistException(
                "Variable {} not exist in the config file".format(name))

    def reload(self):
        """
        Remove file from memoize variable, return again the content of the file and set the configuration again
        :return: None
        """
        config_src = self._loader.reload(anyconfig.load)
        self.set_config(config_src)

    def __setattr__(self, name, value, *args, **kwargs):
        super(ConfFile, self).__setattr__(name, value)