Skip to content

Commit

Permalink
Improve sanitize path
Browse files Browse the repository at this point in the history
  • Loading branch information
ItalyPaleAle committed Sep 15, 2023
1 parent 258bf43 commit e47ad62
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
23 changes: 14 additions & 9 deletions utils/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,28 @@ import (
)

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

// SanitizePath removes certain problematic characters from path names
func SanitizePath(path string) string {
func SanitizePath(str string) string {
// Unicode normalization
path = norm.NFKC.String(path)
str = norm.NFKC.String(str)

// Replace all back slashes with a forward slash
path = strings.ReplaceAll(path, "\\", "/")
str = strings.ReplaceAll(str, "\\", "/")

// Sanitize the string
path = sanitizePathRegexp.ReplaceAllString(path, "")
// Remove invalid characters
str = sanitizePathRegexp.ReplaceAllString(str, "")

// Replace all consecutive slashes with a single one
path = slashConsolidateRegexp.ReplaceAllString(path, "/")
// Clean the path
str = path.Clean(str)
if str == "/" || str == "." {
return ""
}

// Trim the ending slash if present
str = strings.TrimSuffix(str, "/")

return path
return str
}

var mimeTypeRegex = regexp.MustCompile("^(application|audio|font|image|model|text|video)\\/([a-z0-9-+*.]+)")
Expand Down
1 change: 0 additions & 1 deletion utils/functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ func TestSanitizePath(t *testing.T) {
{"foo\\bar", "foo/bar"},
{"foo\\bar\\2", "foo/bar/2"},
// Replace multiple slashes with a single one
{"//", "/"},
{"//aa", "/aa"},
{"hello////world", "hello/world"},
{"hello////world//aa", "hello/world/aa"},
Expand Down

0 comments on commit e47ad62

Please sign in to comment.