使用Python实现一个安全的配置文件管理工具,要求支持配置加密和环境变量注入。请描述核心设计思路。

以下是一个安全的配置文件管理工具的核心设计思路:

  1. 配置文件格式选择 使用常见的配置文件格式,如 JSON 或 YAML,这些格式易于读写且支持嵌套结构。例如:

    database:
      host: "localhost"
      port: 3306
      username: "admin"
      password: "encrypted_password"
    
  2. 环境变量注入 支持通过环境变量动态替换配置文件中的占位符。例如,如果配置文件中存在 {{ ENV_DB_HOST }},则可以替换为实际环境变量的值。

    import os
    
    def inject_env_vars(config):
        for key, value in config.items():
            if isinstance(value, str) and value.startswith("{{ ") and value.endswith(" }}"):
                env_var = value[3:-3].strip()
                config[key] = os.getenv(env_var, "")
            elif isinstance(value, dict):
                inject_env_vars(value)
        return config
    
  3. 配置加密 使用对称加密算法(如 AES)对敏感配置项加密,确保数据在存储时安全。加密密钥可以通过环境变量或密钥管理服务(如 AWS KMS)获取。

    from cryptography.fernet import Fernet
    
    def encrypt_config(config, key):
        fernet = Fernet(key)
        encrypted_config = {}
        for k, v in config.items():
            if k == "password" or k.endswith("_secret"):
                encrypted_config[k] = fernet.encrypt(v.encode()).decode()
            else:
                encrypted_config[k] = v
        return encrypted_config
    
  4. 配置解密 在应用启动时,解密配置文件中加密的敏感数据。

    def decrypt_config(config, key):
        fernet = Fernet(key)
        decrypted_config = {}
        for k, v in config.items():
            if k == "password" or k.endswith("_secret"):
                decrypted_config[k] = fernet.decrypt(v.encode()).decode()
            else:
                decrypted_config[k] = v
        return decrypted_config
    
  5. 配置文件加载 提供一个统一的接口加载配置文件,并实现环境变量注入和解密逻辑。

    import yaml
    
    class ConfigManager:
        def __init__(self, config_path, encryption_key=None):
            self.config_path = config_path
            self.encryption_key = encryption_key
    
        def load_config(self):
            with open(self.config_path, "r") as file:
                config = yaml.safe_load(file)
            config = inject_env_vars(config)
            if self.encryption_key:
                config = decrypt_config(config, self.encryption_key)
            return config
    
  6. 错误处理与日志记录 在配置文件加载和解密过程中捕获异常并记录日志,以便快速排查问题。

    import logging
    
    logging.basicConfig(level=logging.INFO)
    
    try:
        config_manager = ConfigManager("config.yaml", os.getenv("CONFIG_KEY"))
        config = config_manager.load_config()
    except Exception as e:
        logging.error(f"Failed to load config: {e}")
        raise
    
  7. 测试与验证 编写单元测试和集成测试,确保配置文件加载、环境变量注入和加密解密功能正确。

    import unittest
    
    class TestConfigManager(unittest.TestCase):
        def test_env_injection(self):
            os.environ["DB_HOST"] = "test_host"
            config = {"host": "{{ DB_HOST }}"}
            result = inject_env_vars(config)
            self.assertEqual(result["host"], "test_host")
    

通过上述设计,可以实现一个安全、灵活且易于维护的配置文件管理工具。它既能保护敏感数据,又能适应不同的运行时环境。