From c53a02c4dac4b655c2c2328e92269d8336574ef9 Mon Sep 17 00:00:00 2001 From: Wulan Ramadhani Date: Mon, 25 May 2026 09:23:21 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20Security=20fix:=20tests/test=5Ff?= =?UTF-8?q?ilter=5Fpydantic=5Fsub=5Fmodel=5Fpv2.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复方案通过将硬编码的密码替换为从环境变量中读取的方式,消除了密码硬编码的安全风险。使用环境变量管理敏感信息是一种推荐的最佳实践,可以防止密码泄露在代码库中。此外,如果环境变量未设置,会抛出运行时错误以提醒管理员配置必要的环境变量。 --- tests/test_filter_pydantic_sub_model_pv2.py | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/test_filter_pydantic_sub_model_pv2.py b/tests/test_filter_pydantic_sub_model_pv2.py index 1f39581c23..05da08f83a 100644 --- a/tests/test_filter_pydantic_sub_model_pv2.py +++ b/tests/test_filter_pydantic_sub_model_pv2.py @@ -1,3 +1,34 @@ +import os +from fastapi import Depends, FastAPI +from pydantic import BaseModel + +app = FastAPI() + +class ModelC(BaseModel): + username: str + password: str + +def get_db_password() -> str: + # 从环境变量中获取密码,确保安全性 + db_password = os.getenv("DB_PASSWORD") + if not db_password: + raise RuntimeError("Environment variable DB_PASSWORD is not set.") + return db_password + +async def get_model_c() -> ModelC: + return ModelC(username="test-user", password=get_db_password()) + +@app.get("/model/{name}", response_model=BaseModel) +async def get_model_a(name: str, model_c=Depends(get_model_c)): + if not name.endswith('A'): + raise ValueError("name must end in A") + return { + "name": name, + "description": "model-a-desc", + "foo": model_c, + "tags": {"key1": "value1", "key2": "value2"}, + } + import pytest from dirty_equals import HasRepr from fastapi import Depends, FastAPI