Skip to content

Commit abe44d3

Browse files
authored
feat: 优化获取和更新模型设置的apiKey处理逻辑,增加apiKey掩码功能以增强安全性
1 parent 38fb32a commit abe44d3

File tree

1 file changed

+31
-16
lines changed

1 file changed

+31
-16
lines changed

opencontext/server/routes/settings.py

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,16 @@ async def get_model_settings(
6868
获取当前模型配置
6969
"""
7070
try:
71+
def _mask_api_key(raw: str) -> str:
72+
# 直接硬编码:保留前4后2,中间 ***
73+
if not raw:
74+
return ""
75+
if len(raw) <= 6: # 4 + 2
76+
return raw[0] + "***" if len(raw) > 1 else "***"
77+
return f"{raw[:4]}***{raw[-2:]}"
7178
# 从全局配置获取当前设置
7279
global_config = GlobalConfig.get_instance()
7380
config = global_config.get_config()
74-
7581
if not config:
7682
raise HTTPException(status_code=500, detail="配置未初始化")
7783

@@ -84,16 +90,7 @@ async def get_model_settings(
8490
platform = vlm_config.get("provider", "")
8591

8692
# 构造响应 - 使用掩码
87-
def _mask_key(raw: str) -> str:
88-
"""对密钥做掩码:保持前4后2,中间替换为***,长度不足时简单处理。
89-
不在任何情况下回显原始密钥。"""
90-
if not raw:
91-
return ""
92-
if len(raw) <= 6:
93-
return raw[0] + "***" if len(raw) > 1 else "***"
94-
return f"{raw[:4]}***{raw[-2:]}"
95-
96-
masked_key = _mask_key(vlm_config.get("api_key", ""))
93+
masked_key = _mask_api_key(vlm_config.get("api_key", ""))
9794
# 注意:apiKey 字段返回空串以兼容老客户端字段存在性,但不泄露明文
9895
model_settings = ModelSettingsVO(
9996
modelPlatform=platform,
@@ -112,7 +109,6 @@ def _mask_key(raw: str) -> str:
112109
logger.exception(f"获取模型设置失败: {e}")
113110
return convert_resp(code=500, status=500, message=f"获取模型设置失败: {str(e)}")
114111

115-
116112
@router.post("/api/model_settings/update")
117113
async def update_model_settings(
118114
request: UpdateModelSettingsRequest,
@@ -123,8 +119,26 @@ async def update_model_settings(
123119
"""
124120
with _config_lock:
125121
try:
126-
# 验证请求
127-
if not request.config.apiKey:
122+
def _is_masked_api_key(val: str) -> bool:
123+
# 直接硬编码:包含 *** 且不以 *** 结尾 且长度>=6
124+
if not val:
125+
return False
126+
return ("***" in val) and not val.endswith("***") and len(val) >= 6
127+
global_config = GlobalConfig.get_instance()
128+
current_cfg = global_config.get_config() or {}
129+
current_vlm_key = (current_cfg.get("vlm_model") or {}).get("api_key", "")
130+
131+
incoming_key = request.config.apiKey
132+
keep_original = _is_masked_api_key(incoming_key)
133+
134+
if not incoming_key and not current_vlm_key:
135+
# 没有任何真实 key
136+
raise HTTPException(status_code=400, detail="api key cannot be empty")
137+
138+
# 如果是掩码表示不修改;否则使用新 key
139+
final_api_key = current_vlm_key if keep_original else incoming_key
140+
141+
if not final_api_key:
128142
raise HTTPException(status_code=400, detail="api key cannot be empty")
129143
if not request.config.modelId:
130144
raise HTTPException(status_code=400, detail="vlm model cannot be empty")
@@ -139,14 +153,14 @@ async def update_model_settings(
139153
new_settings = {
140154
"vlm_model": {
141155
"base_url": request.config.baseUrl,
142-
"api_key": request.config.apiKey,
156+
"api_key": final_api_key,
143157
"model": request.config.modelId,
144158
"provider": request.config.modelPlatform,
145159
"temperature": 0.7
146160
},
147161
"embedding_model": {
148162
"base_url": request.config.baseUrl,
149-
"api_key": request.config.apiKey,
163+
"api_key": final_api_key,
150164
"model": request.config.embeddingModelId,
151165
"provider": request.config.modelPlatform,
152166
"output_dim": 2048
@@ -191,6 +205,7 @@ async def update_model_settings(
191205
except HTTPException:
192206
raise
193207
except Exception as e:
208+
logger.error(f"更新模型设置失败: {e}")
194209
return convert_resp(
195210
code=500,
196211
status=500,

0 commit comments

Comments
 (0)