mirror of
https://github.com/go-gitea/gitea
synced 2025-07-22 18:28:37 +00:00
Support sanitising the URL by removing extra slashes in the URL (#21333)
Changes in this PR : Strips incoming request URL of additional slashes (/). For example an input like `https://git.data.coop//halfd/new-website.git` is translated to `https://git.data.coop/halfd/new-website.git` Fixes https://github.com/go-gitea/gitea/issues/20462 Fix #23242 --------- Co-authored-by: zeripath <art27@cantab.net> Co-authored-by: Jason Song <i@wolfogre.com> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
@@ -16,7 +16,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/web/routing"
|
||||
|
||||
"github.com/chi-middleware/proxy"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
chi "github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// Middlewares returns common middlewares
|
||||
@@ -48,7 +48,8 @@ func Middlewares() []func(http.Handler) http.Handler {
|
||||
handlers = append(handlers, proxy.ForwardedHeaders(opt))
|
||||
}
|
||||
|
||||
handlers = append(handlers, middleware.StripSlashes)
|
||||
// Strip slashes.
|
||||
handlers = append(handlers, stripSlashesMiddleware)
|
||||
|
||||
if !setting.Log.DisableRouterLog {
|
||||
handlers = append(handlers, routing.NewLoggerHandler())
|
||||
@@ -81,3 +82,33 @@ func Middlewares() []func(http.Handler) http.Handler {
|
||||
})
|
||||
return handlers
|
||||
}
|
||||
|
||||
func stripSlashesMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
|
||||
var urlPath string
|
||||
rctx := chi.RouteContext(req.Context())
|
||||
if rctx != nil && rctx.RoutePath != "" {
|
||||
urlPath = rctx.RoutePath
|
||||
} else if req.URL.RawPath != "" {
|
||||
urlPath = req.URL.RawPath
|
||||
} else {
|
||||
urlPath = req.URL.Path
|
||||
}
|
||||
|
||||
sanitizedPath := &strings.Builder{}
|
||||
prevWasSlash := false
|
||||
for _, chr := range strings.TrimRight(urlPath, "/") {
|
||||
if chr != '/' || !prevWasSlash {
|
||||
sanitizedPath.WriteRune(chr)
|
||||
}
|
||||
prevWasSlash = chr == '/'
|
||||
}
|
||||
|
||||
if rctx == nil {
|
||||
req.URL.Path = sanitizedPath.String()
|
||||
} else {
|
||||
rctx.RoutePath = sanitizedPath.String()
|
||||
}
|
||||
next.ServeHTTP(resp, req)
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user