mirror of
https://codeberg.org/davrot/forgejo.git
synced 2025-06-24 02:00:04 +02:00
Drag and Drop UI: Modifies the SanitizePath approach for path handed over from dropzone.js. Add tests to check the algorithm.
This commit is contained in:
parent
8f5c3b2227
commit
4383c403c9
3 changed files with 105 additions and 34 deletions
39
services/repository/files/pathutils.go
Normal file
39
services/repository/files/pathutils.go
Normal file
|
@ -0,0 +1,39 @@
|
|||
package files
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var fileNameComponentSanitizeRegexp = regexp.MustCompile(`(?i)\.\.|[<>:\"/\\|?*\x{0000}-\x{001F}]|^(con|prn|aux|nul|com\d|lpt\d)$`)
|
||||
|
||||
// SanitizePath cleans and validates a file path
|
||||
func SanitizePath(inputPath string) (string, error) {
|
||||
// Normalize path separators
|
||||
s := strings.ReplaceAll(inputPath, "\\", "/")
|
||||
// Clean the path
|
||||
s = path.Clean(s)
|
||||
// Split the path components
|
||||
pathComponents := strings.Split(s, "/")
|
||||
// Sanitize each path component
|
||||
var sanitizedComponents []string
|
||||
for _, component := range pathComponents {
|
||||
// Trim whitespace and apply regex sanitization
|
||||
sanitizedComponent := strings.TrimSpace(fileNameComponentSanitizeRegexp.ReplaceAllString(component, "_"))
|
||||
|
||||
// Skip empty components after sanitization
|
||||
if sanitizedComponent != "" {
|
||||
sanitizedComponents = append(sanitizedComponents, sanitizedComponent)
|
||||
}
|
||||
}
|
||||
// Check if we have any components left after sanitization
|
||||
if len(sanitizedComponents) == 0 {
|
||||
return "", fmt.Errorf("path became empty after sanitization")
|
||||
}
|
||||
// Reconstruct the path
|
||||
reconstructedPath := path.Join(sanitizedComponents...)
|
||||
return reconstructedPath, nil
|
||||
}
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue