From 75ef8f32a0b540b1b8c64dcb00222760ccbb3125 Mon Sep 17 00:00:00 2001 From: "tao.chen" <93983997+taochen-ct@users.noreply.github.com> Date: Mon, 24 Aug 2026 10:59:07 +0800 Subject: [PATCH] chore: encrypt_secret.py --- common/pyproject.toml | 1 + common/src/common/config.py | 58 ++++++++++++++++++++++++++++++------- docker-compose.yml | 4 +++ scripts/encrypt_secret.py | 24 +++++++++++++++ uv.lock | 2 ++ 5 files changed, 78 insertions(+), 11 deletions(-) create mode 100644 scripts/encrypt_secret.py diff --git a/common/pyproject.toml b/common/pyproject.toml index 5f32862..94a45fb 100644 --- a/common/pyproject.toml +++ b/common/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ "bcrypt>=4.0,<4.1", "aiofiles>=25.1.0", "aioboto3>=15.5.0", + "cryptography>=49.0.0", ] [build-system] diff --git a/common/src/common/config.py b/common/src/common/config.py index f88068f..2fd1b75 100644 --- a/common/src/common/config.py +++ b/common/src/common/config.py @@ -17,13 +17,43 @@ Rules for adding a new variable: from __future__ import annotations +import base64 +import os from functools import lru_cache -from typing import Annotated +from typing import Annotated, Any +from venv import logger -from pydantic import Field, field_validator +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from pydantic import Field, field_validator, model_validator from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict +# ── AES 解密核心函数 ──────────────────────────────────────────────────────── +def _decrypt_value(cipher_text: str) -> str: + """解密 ENC(...) 格式的字符串。密钥从环境变量 APP_CONFIG_SECRET_KEY 获取。""" + if not (cipher_text.startswith("ENC(") and cipher_text.endswith(")")): + return cipher_text + + secret_key = os.getenv("APP_CONFIG_SECRET_KEY") + if not secret_key: + raise RuntimeError( + "致命错误: 检测到配置项包含 ENC(...) 密文,但系统环境变量 " + "APP_CONFIG_SECRET_KEY 未设置!" + ) + + raw_payload = cipher_text[4:-1] + try: + data = base64.b64decode(raw_payload) + nonce, ciphertext = data[:12], data[12:] + # 将传入的 key 补全或截断为 32 字节 (AES-256) + key_bytes = secret_key.encode("utf-8").ljust(32, b"\0")[:32] + cipher = AESGCM(key_bytes) + decrypted = cipher.decrypt(nonce, ciphertext, None) + return decrypted.decode("utf-8") + except Exception as e: + raise ValueError(f"配置项解密失败,请检查密钥或密文正确性: {e}") from e + + class Settings(BaseSettings): # ── database ────────────────────────────────────────────────── database_url: str = Field( @@ -95,7 +125,6 @@ class Settings(BaseSettings): @field_validator("audit_excluded_paths", mode="before") @classmethod def _split_audit_paths(cls, v): - # env 进来是 "a,b,c";代码里直接传 list 也行 if isinstance(v, str): return [s.strip() for s in v.split(",") if s.strip()] return v @@ -223,13 +252,21 @@ class Settings(BaseSettings): ) # ── readiness probes ────────────────────────────────────────── - readiness_targets: str = Field( - default="", - description=( - "Comma-separated host:port list checked by /health/ready. " - "Empty disables the check." - ), - ) + readiness_targets: str = Field(default="") + + # ── 全局密文拦截器 ─────────────────────────────────────────── + @model_validator(mode="before") + @classmethod + def _decrypt_encrypted_fields(cls, values: dict[str, Any]) -> dict[str, Any]: + """在 Pydantic 赋值前自动扫描所有 str 类型的环境变量,解密 ENC(...)""" + if not isinstance(values, dict): + return values + + for key, val in values.items(): + if isinstance(val, str) and val.startswith("ENC("): + values[key] = _decrypt_value(val) + print(values[key]) + return values model_config = SettingsConfigDict( env_file=".env", @@ -247,5 +284,4 @@ def get_settings() -> Settings: settings: Settings = get_settings() - __all__ = ["Settings", "get_settings", "settings"] diff --git a/docker-compose.yml b/docker-compose.yml index 53ff630..337b202 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -25,6 +25,7 @@ services: INITIAL_ADMIN_PASSWORD: ${INITIAL_ADMIN_PASSWORD:-admin12345} UV_OFFLINE: "1" UV_NO_SYNC: "1" + APP_CONFIG_SECRET_KEY: ${APP_CONFIG_SECRET_KEY:?APP_CONFIG_SECRET_KEY is required} web: build: @@ -100,6 +101,7 @@ services: READINESS_TARGETS: ${MYSQL_HOST:?MYSQL_HOST is required}:${MYSQL_PORT:-3306},runtime:8000 UV_OFFLINE: "1" UV_NO_SYNC: "1" + APP_CONFIG_SECRET_KEY: ${APP_CONFIG_SECRET_KEY:?APP_CONFIG_SECRET_KEY is required} depends_on: migrate: condition: service_completed_successfully @@ -164,6 +166,7 @@ services: RCLONE_CONFIG_S3_REGION: other UV_OFFLINE: "1" UV_NO_SYNC: "1" + APP_CONFIG_SECRET_KEY: ${APP_CONFIG_SECRET_KEY:?APP_CONFIG_SECRET_KEY is required} volumes: - ${PWD}:/app - ./data:/data @@ -213,6 +216,7 @@ services: READINESS_TARGETS: ${MYSQL_HOST:?MYSQL_HOST is required}:${MYSQL_PORT:-3306},backend:8000 UV_OFFLINE: "1" UV_NO_SYNC: "1" + APP_CONFIG_SECRET_KEY: ${APP_CONFIG_SECRET_KEY:?APP_CONFIG_SECRET_KEY is required} depends_on: backend: condition: service_healthy diff --git a/scripts/encrypt_secret.py b/scripts/encrypt_secret.py new file mode 100644 index 0000000..3dbbe3a --- /dev/null +++ b/scripts/encrypt_secret.py @@ -0,0 +1,24 @@ +""" +@Time :2026/8/24 +@Author :tao.chen +""" +import base64 +import os +import sys + +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + +def encrypt(plain_text: str, secret_key: str) -> str: + key_bytes = secret_key.encode("utf-8").ljust(32, b"\0")[:32] + cipher = AESGCM(key_bytes) + nonce = os.urandom(12) + ciphertext = cipher.encrypt(nonce, plain_text.encode("utf-8"), None) + payload = base64.b64encode(nonce + ciphertext).decode("utf-8") + return f"ENC({payload})" + +if __name__ == "__main__": + if len(sys.argv) < 3: + print("Usage: python encrypt_secret.py ") + sys.exit(1) + print(encrypt(sys.argv[2], sys.argv[1])) diff --git a/uv.lock b/uv.lock index b921fbb..c6dcd08 100644 --- a/uv.lock +++ b/uv.lock @@ -685,6 +685,7 @@ dependencies = [ { name = "apscheduler" }, { name = "asyncmy" }, { name = "bcrypt" }, + { name = "cryptography" }, { name = "fastapi" }, { name = "greenlet" }, { name = "loguru" }, @@ -705,6 +706,7 @@ requires-dist = [ { name = "apscheduler", specifier = ">=3.11.3" }, { name = "asyncmy", specifier = "==0.2.11" }, { name = "bcrypt", specifier = ">=4.0,<4.1" }, + { name = "cryptography", specifier = ">=49.0.0" }, { name = "fastapi", specifier = "==0.116.1" }, { name = "greenlet", specifier = ">=3.0.0" }, { name = "loguru", specifier = ">=0.7.2" },