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.
This commit is contained in:
wizardchen
2026-06-05 19:33:10 +08:00
committed by lyingbug
parent b820e690f0
commit 28de82a92e
+9 -1
View File
@@ -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 {