refactor: safer query handling
https://github.com/ipfs/go-ipfs/pull/7930#discussion_r597246135
Marcin Rataj committed
Mar 18, 2021 at 23:48 UTC
a35ffee1364b72e50f66fdd1a03f7a3665d99309
1 file changed
+8
-3
core/corehttp/gateway_handler.go
+8
-3
@@ -238,7 +238,7 @@ func (i *gatewayHandler) getOrHeadHandler(w http.ResponseWriter, r *http.Request
238
239
parsedPath := ipath.New(urlPath)
240
if pathErr := parsedPath.IsValid(); pathErr != nil {
241
- if fixupSuperfluousNamespace(w, r, urlPath) {
241
+ if fixupSuperfluousNamespace(w, urlPath, r.URL.RawQuery) {
242
// the error was due to redundant namespace, which we were able to fix
243
// by returning error/redirect page, nothing left to do here
244
return
@@ -813,7 +813,7 @@ func preferred404Filename(acceptHeaders []string) (string, string, error) {
813
// 'intended' path is valid. This is in case gremlins were tickled
814
// wrong way and user ended up at /ipfs/ipfs/{cid} or /ipfs/ipns/{id}
815
// like in bafybeien3m7mdn6imm425vc2s22erzyhbvk5n3ofzgikkhmdkh5cuqbpbq :^))
816
-func fixupSuperfluousNamespace(w http.ResponseWriter, r *http.Request, urlPath string) bool {
816
+func fixupSuperfluousNamespace(w http.ResponseWriter, urlPath string, urlQuery string) bool {
817
if !(strings.HasPrefix(urlPath, "/ipfs/ipfs/") || strings.HasPrefix(urlPath, "/ipfs/ipns/")) {
818
return false // not a superfluous namespace
819
}
@@ -821,7 +821,12 @@ func fixupSuperfluousNamespace(w http.ResponseWriter, r *http.Request, urlPath s
821
if err := intendedPath.IsValid(); err != nil {
822
return false // not a valid path
823
}
824
- intendedURL := strings.Replace(r.URL.String(), urlPath, intendedPath.String(), 1)
824
+ intendedURL := intendedPath.String()
825
+ if urlQuery != "" {
826
+ // we render HTML, so ensure query entries are properly escaped
827
+ q, _ := url.ParseQuery(urlQuery)
828
+ intendedURL = intendedURL + "?" + q.Encode()
829
+ }
830
// return HTTP 400 (Bad Request) with HTML error page that:
831
// - points at correct canonical path via <link> header
832
// - displays human-readable error