From e16b358aa319e62671f0994d61a6e8bbf5c9f5d9 Mon Sep 17 00:00:00 2001 From: LexLuthr <88259624+LexLuthr@users.noreply.github.com> Date: Fri, 9 Aug 2024 05:44:34 +0400 Subject: [PATCH] feat: decode multihash string for B58 and Hex (#2630) * decode multihash string for B58 and Hex * If bad encoding, show both b58 and hex errors * Add unit tests, update error message --------- Co-authored-by: gammazero <11790789+gammazero@users.noreply.github.com> --- server/find/server.go | 13 +++++++++---- server/find/server_test.go | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/server/find/server.go b/server/find/server.go index 946439057..138b01a66 100644 --- a/server/find/server.go +++ b/server/find/server.go @@ -14,7 +14,7 @@ import ( "github.com/ipfs/go-cid" logging "github.com/ipfs/go-log/v2" - indexer "github.com/ipni/go-indexer-core" + "github.com/ipni/go-indexer-core" coremetrics "github.com/ipni/go-indexer-core/metrics" "github.com/ipni/go-libipni/apierror" "github.com/ipni/go-libipni/find/model" @@ -181,9 +181,14 @@ func (s *Server) findMultihash(w http.ResponseWriter, r *http.Request) { mhVar := path.Base(r.URL.Path) m, err := multihash.FromB58String(mhVar) if err != nil { - log.Errorw("error decoding multihash", "multihash", mhVar, "err", err) - httpserver.HandleError(w, err, "find") - return + var hexErr error + m, hexErr = multihash.FromHexString(mhVar) + if hexErr != nil { + msg := "find: input is not a valid base58 or hex encoded multihash" + log.Errorw(msg, "multihash", mhVar, "err", err, "hexErr", hexErr) + http.Error(w, msg, http.StatusBadRequest) + return + } } s.getIndexes(w, []multihash.Multihash{m}, stream) } diff --git a/server/find/server_test.go b/server/find/server_test.go index 98da4f42c..518d41b16 100644 --- a/server/find/server_test.go +++ b/server/find/server_test.go @@ -99,6 +99,17 @@ func TestServer_CORSWithExpectedContentType(t *testing.T) { reqUrl: "/multihash/" + mhs[0].B58String(), wantContentType: "application/json", }, + { + reqMethod: http.MethodGet, + reqUrl: "/multihash/" + mhs[0].HexString(), + wantContentType: "application/json", + }, + { + reqMethod: http.MethodGet, + reqUrl: "/multihash/" + "deadbeef", + wantContentType: "application/json", + statusCode: http.StatusBadRequest, + }, { reqMethod: http.MethodPost, reqUrl: "/multihash", @@ -115,6 +126,12 @@ func TestServer_CORSWithExpectedContentType(t *testing.T) { reqUrl: "/", wantContentType: "text/html", }, + { + reqMethod: http.MethodGet, + reqUrl: "/multihash/1qaai0lO_aa^", + wantContentType: "application/json", + statusCode: http.StatusBadRequest, + }, } cl := http.DefaultClient