diff --git a/rwriter/response_writer.go b/rwriter/response_writer.go index 022bab7..8942947 100644 --- a/rwriter/response_writer.go +++ b/rwriter/response_writer.go @@ -1,6 +1,7 @@ package rwriter import ( + "encoding/hex" "encoding/json" "errors" "fmt" @@ -84,9 +85,13 @@ func New(w http.ResponseWriter, r *http.Request, options ...Option) (*ResponseWr } switch pathType { case opts.mhPathType: - b, err = base58.Decode(strings.TrimSpace(path.Base(r.URL.Path))) + mhStr := strings.TrimSpace(path.Base(r.URL.Path)) + b, err = base58.Decode(mhStr) if err != nil { - return nil, apierror.New(multihash.ErrInvalidMultihash, http.StatusBadRequest) + b, err = hex.DecodeString(mhStr) + if err != nil { + return nil, apierror.New(multihash.ErrInvalidMultihash, http.StatusBadRequest) + } } mh = multihash.Multihash(b) cidKey = cid.NewCidV1(cid.Raw, mh) diff --git a/rwriter/response_writer_test.go b/rwriter/response_writer_test.go index e295bd2..0a54fc7 100644 --- a/rwriter/response_writer_test.go +++ b/rwriter/response_writer_test.go @@ -2,6 +2,7 @@ package rwriter_test import ( "bytes" + "encoding/hex" "io" "net/http" "net/http/httptest" @@ -9,6 +10,7 @@ import ( "testing" "github.com/ipni/go-libipni/rwriter" + "github.com/mr-tron/base58" "github.com/stretchr/testify/require" ) @@ -87,4 +89,32 @@ func TestResponseWriter(t *testing.T) { require.NoError(t, err) require.Equal(t, http.StatusBadRequest, res.StatusCode) require.Equal(t, "unsupported resource type", strings.TrimSpace(string(body))) + + // Check that invalid multihash is handled. + req, err = http.NewRequest(http.MethodGet, ts.URL+"/multihash/aflk324vecr-903r-0", nil) + require.NoError(t, err) + req.Header.Set("Accept", "application/json") + res, err = cli.Do(req) + require.NoError(t, err) + _, err = io.Copy(io.Discard, res.Body) + require.NoError(t, err) + res.Body.Close() + require.NoError(t, err) + require.Equal(t, http.StatusBadRequest, res.StatusCode) + + b, err := base58.Decode("2DrjgbM2tfcpUE5imXMv3HnzryEaxd1FKh8DWMDEgtFkL7MDvT") + require.NoError(t, err) + + // Check that hex multihash is handled. + req, err = http.NewRequest(http.MethodGet, ts.URL+"/multihash/"+hex.EncodeToString(b), nil) + require.NoError(t, err) + req.Header.Set("Accept", "application/json") + res, err = cli.Do(req) + require.NoError(t, err) + body, err = io.ReadAll(res.Body) + res.Body.Close() + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, testHeaderVal, res.Header.Get(testHeaderKey)) + require.Equal(t, "ok", strings.TrimSpace(string(body))) }