From 28de82a92eb92dc98cd612bc1c484d361382bc0b Mon Sep 17 00:00:00 2001 From: wizardchen Date: Fri, 5 Jun 2026 19:33:10 +0800 Subject: [PATCH] refactor(chat): improve model name sanitization and path validation - Updated the sanitization logic in `newStreamPacketDumper` to exclude the '.' character, enhancing security against path traversal vulnerabilities. - Added checks to ensure the cleaned file path remains within the specified directory, preventing unauthorized access to the filesystem. - Improved overall robustness of file handling by enforcing stricter path validation rules. --- internal/models/chat/stream_raw_dump.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/internal/models/chat/stream_raw_dump.go b/internal/models/chat/stream_raw_dump.go index 7ed7e4e3..fad3c20b 100644 --- a/internal/models/chat/stream_raw_dump.go +++ b/internal/models/chat/stream_raw_dump.go @@ -49,7 +49,7 @@ func newStreamPacketDumper(modelName string, request any) *streamPacketDumper { safeModel := strings.Map(func(r rune) rune { switch { - case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_', r == '.': + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_': return r default: return '_' @@ -60,7 +60,15 @@ func newStreamPacketDumper(modelName string, request any) *streamPacketDumper { } name := fmt.Sprintf("llm_stream_%s_%s.jsonl", safeModel, time.Now().Format("20060102T150405.000000000")) + // Defense-in-depth against path traversal: the model name is externally + // controlled, so force the file to live directly under dir and verify the + // cleaned path cannot escape it. + name = filepath.Base(filepath.Clean("/" + name)) + dir = filepath.Clean(dir) path := filepath.Join(dir, name) + if rel, err := filepath.Rel(dir, path); err != nil || rel != name { + return nil + } f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil {