通过aumbry支持加密和非加密配置

时间:2018-09-26 17:11:47

标签: python configuration python-cryptography aumbry

我们有一个python应用程序,该应用程序通过 aumbry 加载config.yml。为了生产目的,我们需要使用 fernet 加密此配置,该配置可以无缝加载。

我们希望能够以透明方式加载未加密和已加密的文件,例如,如果发现未加载的文件,则加载未加密的文件;如果(生产)未加载的文件,则加载未加密的文件。到目前为止,我们已经实现了这一点。

加密

import cryptography.Fernet as fn
from os.path import split, splitext

def _encrypt_file(path, key):
    with open(path, 'rb') as infile:
        file_data = infile.read()
        nc_data= fn(key).encrypt(file_data)
        infile.close()

        base_path, filename = split(path)
        name, _ = splitext(filename)
        nc_name = "{}.{}".format(name, 'nc')
        with open(join(base_path, nc_name), 'wb') as outfile:
            outfile.write(nc_data)
            outfile.close()

Aumbry配置

from aumbry.errors import LoadError

def _get_configuration():
    return aumbry.load(
        aumbry.FILE,
        AppConfig,
        options={
            'CONFIG_FILE_PATH': "config.yml"            
        }
    )

def _get_encrypted_configuration():
    return aumbry.load(
        aumbry.FERNET,
        AppConfig,
        options={
            'CONFIG_FILE_PATH': "config.nc",
            'CONFIG_FILE_FERNET_KEY': 'bZhF6nN4A6fhVBPtru2dG1_6d7i0d_B2FxmsybjtE-g='
        }
    )
def load_config():
    """General method to load configuration"""
    try:
        return _get_configuration()
    except LoadError:
        try: 
            return _get_encrypted_configuration()
        except LoadError:
            return None
  • 是否有更优雅的方法来实现此行为?

2 个答案:

答案 0 :(得分:2)

取决于构建python应用程序的框架,通常可以使用某种全局“模式”值。

例如,

烧瓶使用FLASK_ENV环境变量,可以将其设置为developmentproduction。在应用程序中,您可以使用

app.config['DEBUG']  # True if FLASK_ENV is "development"

区分这两种模式。

在您的情况下,可以将ambury加载程序重构为:

config_loader_cls = EncryptedConfigLoader if environment=='production' else PlainConfigLoader

如果配置未加密 以获得更高的安全性,我将走得更远,让EncryptedConfigLoader失败。

答案 1 :(得分:2)

有一些解决方案:

a)加密的文件使用与未加密的对应文件不同的文件名。例如,名称为“ config.yml”的未加密文件可以重命名为“ config_en.yml”。这可能不是您的选择。

b)我注意到“ config.yml”的内容通常具有“ version:2”。您只需要使用Python检查"version:是否为in文件,如果是,则未加密。