fix: handle urls with multiple slashes (#16527)

Fixes: https://github.com/coder/coder/issues/9877

This PR introduces another middleware to rewrite URLs when multiple
slashes are used.
This commit is contained in:
Marcin Tojek
2025-02-12 09:23:28 +01:00
committed by GitHub
parent 5ec385b36b
commit b3964087c4
3 changed files with 104 additions and 0 deletions

View File

@ -788,6 +788,7 @@ func New(options *Options) *API {
httpmw.AttachRequestID,
httpmw.ExtractRealIP(api.RealIPConfig),
httpmw.Logger(api.Logger),
singleSlashMW,
rolestore.CustomRoleMW,
prometheusMW,
// Build-Version is helpful for debugging.
@ -1731,3 +1732,31 @@ func ReadExperiments(log slog.Logger, raw []string) codersdk.Experiments {
}
return exps
}
var multipleSlashesRe = regexp.MustCompile(`/+`)
func singleSlashMW(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
var path string
rctx := chi.RouteContext(r.Context())
if rctx != nil && rctx.RoutePath != "" {
path = rctx.RoutePath
} else {
path = r.URL.Path
}
// Normalize multiple slashes to a single slash
newPath := multipleSlashesRe.ReplaceAllString(path, "/")
// Apply the cleaned path
// The approach is consistent with: https://github.com/go-chi/chi/blob/e846b8304c769c4f1a51c9de06bebfaa4576bd88/middleware/strip.go#L24-L28
if rctx != nil {
rctx.RoutePath = newPath
} else {
r.URL.Path = newPath
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}