security: sanitize path and uri

This commit is contained in:
yusing
2025-03-22 23:53:33 +08:00
parent 4a5e0b8d81
commit f3840d56af
5 changed files with 106 additions and 11 deletions

View File

@@ -0,0 +1,20 @@
package strutils
import "path"
// SanitizeURI sanitizes a URI reference to ensure it is safe
// It disallows URLs beginning with // or /\ as absolute URLs,
// cleans the URL path to remove any .. or . path elements,
// and ensures the URL starts with a / if it doesn't already
func SanitizeURI(uri string) string {
if uri == "" {
return "/"
}
if uri[0] != '/' {
uri = "/" + uri
}
if len(uri) > 1 && uri[0] == '/' && uri[1] != '/' && uri[1] != '\\' {
return path.Clean(uri)
}
return "/"
}