forked from forgejo/forgejo
Backport #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: Sandeep Bhat <sandyethadka@gmail.com> Co-authored-by: zeripath <art27@cantab.net> Co-authored-by: Jason Song <i@wolfogre.com> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com> Co-authored-by: delvh <leon@kske.dev>
This commit is contained in:
parent
ff96f804b6
commit
a2a9b0f977
2 changed files with 103 additions and 2 deletions
|
@ -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)
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue