refactor: explicit prefix check
https://github.com/ipfs/go-ipfs/pull/7930#discussion_r584001161
Marcin Rataj committed
Mar 18, 2021 at 21:48 UTC
450baef0e9c113e4751b559dd0562f7c98302668
1 file changed
+8
-7
core/corehttp/gateway_handler.go
+8
-7
@@ -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 fixErr := fixupSuperfluousNamespace(w, r, pathErr, urlPath); fixErr == nil {
241
+ if fixupSuperfluousNamespace(w, r, urlPath) {
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,12 +813,13 @@ 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, pathErr error, urlPath string) error {
816
+func fixupSuperfluousNamespace(w http.ResponseWriter, r *http.Request, urlPath string) bool {
817
+ if !(strings.HasPrefix(urlPath, "/ipfs/ipfs/") || strings.HasPrefix(urlPath, "/ipfs/ipns/")) {
818
+ return false // not a superfluous namespace
819
+ }
820
intendedPath := ipath.New(strings.TrimPrefix(urlPath, "/ipfs"))
818
- err := intendedPath.IsValid()
819
- if err != nil {
820
- // not a superfluous namespace
821
- return err
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)
825
// return HTTP 400 (Bad Request) with HTML error page that:
@@ -830,5 +831,5 @@ func fixupSuperfluousNamespace(w http.ResponseWriter, r *http.Request, pathErr e
831
RedirectURL: intendedURL,
832
SuggestedPath: intendedPath.String(),
833
ErrorMsg: fmt.Sprintf("invalid path: %q should be %q", urlPath, intendedPath.String()),
833
- })
834
+ }) == nil
835
}