Skip to content
This repository was archived by the owner on Jul 4, 2025. It is now read-only.

Commit 4a4fff4

Browse files
authored
Merge pull request #1983 from janhq/sanitize_path
Fix: Prevent Path Traversal in File Storage
2 parents ca056e4 + 450b313 commit 4a4fff4

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

engine/repositories/file_fs_repository.cc

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,21 @@ std::filesystem::path FileFsRepository::GetFilePath() const {
1010
return data_folder_path_ / kFileContainerFolderName;
1111
}
1212

13+
std::filesystem::path SanitizePath(const std::filesystem::path & user_input,
14+
const std::filesystem::path & basedir) {
15+
16+
auto abs_base = std::filesystem::canonical(basedir);
17+
std::filesystem::path resolved_path = std::filesystem::weakly_canonical(
18+
std::filesystem::path(basedir) / std::filesystem::path(user_input));
19+
/* Ensure the resolved path is within our basedir */
20+
for (auto p = resolved_path; !p.empty(); p = p.parent_path()) {
21+
if (std::filesystem::equivalent(p, abs_base)) {
22+
return resolved_path;
23+
}
24+
}
25+
return {};
26+
}
27+
1328
cpp::result<void, std::string> FileFsRepository::StoreFile(
1429
OpenAi::File& file_metadata, const char* content, uint64_t length) {
1530
auto file_container_path = GetFilePath();
@@ -18,7 +33,11 @@ cpp::result<void, std::string> FileFsRepository::StoreFile(
1833
}
1934

2035
auto original_filename = file_metadata.filename;
21-
auto file_full_path = file_container_path / original_filename;
36+
auto file_full_path = SanitizePath(original_filename, file_container_path);
37+
38+
if (file_full_path.empty()) {
39+
return cpp::fail("Error resolving path in: " + original_filename);
40+
}
2241

2342
// Handle duplicate filenames
2443
int counter = 1;

0 commit comments

Comments
 (0)