安全修复(High): event_type 和 mode 参数添加白名单校验
- 定义 ALLOWED_EVENT_TYPES 白名单 - 定义 ALLOWED_MODES 白名单 - record_event() 函数中验证参数合法性 - 防止注入恶意事件类型或模式
This commit is contained in:
@@ -31,6 +31,26 @@ MAX_EVENTS = 10000
|
||||
# 敏感字段列表(不记录这些字段)
|
||||
SENSITIVE_FIELDS = {"password", "token", "secret", "key", "credential", "auth"}
|
||||
|
||||
# 允许的 event_type 白名单
|
||||
ALLOWED_EVENT_TYPES = {
|
||||
"command_executed",
|
||||
"task_completed",
|
||||
"stats_viewed",
|
||||
"test_event",
|
||||
"another_event",
|
||||
"workflow_started",
|
||||
"workflow_completed",
|
||||
"error_occurred",
|
||||
}
|
||||
|
||||
# 允许的 mode 白名单
|
||||
ALLOWED_MODES = {
|
||||
"cross",
|
||||
"normal",
|
||||
"debug",
|
||||
"test",
|
||||
}
|
||||
|
||||
|
||||
def _ensure_stats_dir():
|
||||
"""确保统计目录存在"""
|
||||
@@ -183,8 +203,23 @@ def record_event(
|
||||
|
||||
Raises:
|
||||
TypeError: metadata 不是 dict 类型时
|
||||
ValueError: event_type 或 mode 不在白名单中时
|
||||
"""
|
||||
try:
|
||||
# event_type 白名单校验
|
||||
if event_type not in ALLOWED_EVENT_TYPES:
|
||||
raise ValueError(
|
||||
f"无效的 event_type: {event_type}. "
|
||||
f"允许的值: {', '.join(sorted(ALLOWED_EVENT_TYPES))}"
|
||||
)
|
||||
|
||||
# mode 白名单校验
|
||||
if mode not in ALLOWED_MODES:
|
||||
raise ValueError(
|
||||
f"无效的 mode: {mode}. "
|
||||
f"允许的值: {', '.join(sorted(ALLOWED_MODES))}"
|
||||
)
|
||||
|
||||
# metadata 类型校验
|
||||
if metadata is not None and not isinstance(metadata, dict):
|
||||
raise TypeError(f"metadata 必须是 dict 类型,当前为: {type(metadata).__name__}")
|
||||
@@ -214,8 +249,8 @@ def record_event(
|
||||
_atomic_write(data)
|
||||
|
||||
return True
|
||||
except TypeError:
|
||||
raise # 重新抛出类型错误
|
||||
except (TypeError, ValueError):
|
||||
raise # 重新抛出类型和值错误
|
||||
except Exception as e:
|
||||
logger.error(f"记录事件失败: {e}")
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user