fix: prevent path traversal error when knowledge FilePath is empty#1658
Open
ChenRussell wants to merge 1 commit into
Open
fix: prevent path traversal error when knowledge FilePath is empty#1658ChenRussell wants to merge 1 commit into
ChenRussell wants to merge 1 commit into
Conversation
Three related fixes for the issue where a knowledge record with empty
FilePath (from a failed SaveFile during upload) caused a misleading
"path traversal denied" error when trying to preview the file:
1. GetKnowledgeFile: add guard to return a clear error when FilePath
is empty, instead of letting it fall through to the storage layer.
2. normalizePathForBase: return baseDir instead of "." when the input
is empty or whitespace-only, preventing SafePathUnderBase from
resolving "." to the current working directory (which may differ
from baseDir).
3. CreateKnowledgeFromFile: delete the orphan knowledge record when
SaveFile fails, preventing FilePath-empty records from persisting
in the database.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
现象
调用 /api/v1/knowledge/{id}/preview 返回 HTTP 500:
关键日志:
根因
数据库中有一条 knowledge 记录的 file_path 为空字符串。
这条脏数据的产生过程:
CreateKnowledgeFromFile
├── CreateKnowledge() ← 先入库,FilePath 此时为空
├── SaveFile() ← 存文件失败(磁盘满/权限等)
└── return nil, err ← 直接返回,knowledge 记录未清理
CreateKnowledge 和 SaveFile 不是原子操作。SaveFile 失败后 knowledge 已入库但 FilePath 为空,成为孤儿脏数据。
当预览该知识时,空 FilePath 经过 normalizePathForBase 处理:
接着 SafePathUnderBase(baseDir, ".") 将 "." 解析为当前工作目录。当进程工作目录与 baseDir 不同时,被误判为路径遍历攻击,报出误导性错误。
修复
Type of Change
Related Issue
Fixes #
Testing
Checklist
make fmt && make lint && make testpass locallydocs/, Swagger annotations, etc.)Screenshots / Recordings