Skip to content

Commit e47ad62

Browse files
committed
Improve sanitize path
1 parent 258bf43 commit e47ad62

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

utils/functions.go

+14-9
Original file line numberDiff line numberDiff line change
@@ -26,23 +26,28 @@ import (
2626
)
2727

2828
var sanitizePathRegexp = regexp.MustCompile("[#%&{}<>*\\$:!'\"+@\x60|=]")
29-
var slashConsolidateRegexp = regexp.MustCompile("/{2,}")
3029

3130
// SanitizePath removes certain problematic characters from path names
32-
func SanitizePath(path string) string {
31+
func SanitizePath(str string) string {
3332
// Unicode normalization
34-
path = norm.NFKC.String(path)
33+
str = norm.NFKC.String(str)
3534

3635
// Replace all back slashes with a forward slash
37-
path = strings.ReplaceAll(path, "\\", "/")
36+
str = strings.ReplaceAll(str, "\\", "/")
3837

39-
// Sanitize the string
40-
path = sanitizePathRegexp.ReplaceAllString(path, "")
38+
// Remove invalid characters
39+
str = sanitizePathRegexp.ReplaceAllString(str, "")
4140

42-
// Replace all consecutive slashes with a single one
43-
path = slashConsolidateRegexp.ReplaceAllString(path, "/")
41+
// Clean the path
42+
str = path.Clean(str)
43+
if str == "/" || str == "." {
44+
return ""
45+
}
46+
47+
// Trim the ending slash if present
48+
str = strings.TrimSuffix(str, "/")
4449

45-
return path
50+
return str
4651
}
4752

4853
var mimeTypeRegex = regexp.MustCompile("^(application|audio|font|image|model|text|video)\\/([a-z0-9-+*.]+)")

utils/functions_test.go

-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ func TestSanitizePath(t *testing.T) {
4545
{"foo\\bar", "foo/bar"},
4646
{"foo\\bar\\2", "foo/bar/2"},
4747
// Replace multiple slashes with a single one
48-
{"//", "/"},
4948
{"//aa", "/aa"},
5049
{"hello////world", "hello/world"},
5150
{"hello////world//aa", "hello/world/aa"},

0 commit comments

Comments
 (0)