pkg/storj: use proper unquoting of json data in NodeID and PieceID (#2094)

This commit is contained in:
Egon Elbre 2019-06-03 16:29:07 +03:00 committed by Michal Niewrzal
parent 79a0085103
commit 8c0c518621
4 changed files with 22 additions and 6 deletions

View File

@ -7,8 +7,8 @@ import (
"crypto/sha256"
"crypto/x509/pkix"
"database/sql/driver"
"encoding/json"
"math/bits"
"strings"
"github.com/btcsuite/btcutil/base58"
"github.com/zeebo/errs"
@ -220,8 +220,13 @@ func (id *NodeID) Scan(src interface{}) (err error) {
// UnmarshalJSON deserializes a json string (as bytes) to a node ID
func (id *NodeID) UnmarshalJSON(data []byte) error {
var err error
*id, err = NodeIDFromString(strings.Trim(string(data), `"`))
var unquoted string
err := json.Unmarshal(data, &unquoted)
if err != nil {
return err
}
*id, err = NodeIDFromString(unquoted)
if err != nil {
return err
}

View File

@ -153,6 +153,9 @@ func TestNodeID_UnmarshalJSON(t *testing.T) {
err := json.Unmarshal([]byte(`"12vha9oTFnerxYRgeQ2BZqoFrLrnmmf5UWTCY2jA77dF3YvWew7"`), &nodeID)
require.NoError(t, err)
assert.Equal(t, nodeID.String(), "12vha9oTFnerxYRgeQ2BZqoFrLrnmmf5UWTCY2jA77dF3YvWew7")
assert.Error(t, nodeID.UnmarshalJSON([]byte(`""12vha9oTFnerxYRgeQ2BZqoFrLrnmmf5UWTCY2jA77dF3YvWew7""`)))
assert.Error(t, nodeID.UnmarshalJSON([]byte(`{}`)))
}
func TestNewVersionedID(t *testing.T) {

View File

@ -9,7 +9,7 @@ import (
"crypto/sha512"
"database/sql/driver"
"encoding/base32"
"strings"
"encoding/json"
"github.com/zeebo/errs"
)
@ -106,8 +106,13 @@ func (id PieceID) MarshalJSON() ([]byte, error) {
// UnmarshalJSON deserializes a json string (as bytes) to a piece ID
func (id *PieceID) UnmarshalJSON(data []byte) error {
var err error
*id, err = PieceIDFromString(strings.Trim(string(data), `"`))
var unquoted string
err := json.Unmarshal(data, &unquoted)
if err != nil {
return err
}
*id, err = PieceIDFromString(unquoted)
if err != nil {
return err
}

View File

@ -75,4 +75,7 @@ func TestPieceID_UnmarshalJSON(t *testing.T) {
err := json.Unmarshal([]byte(`"`+originalPieceID.String()+`"`), &pieceid)
require.NoError(t, err)
assert.Equal(t, pieceid.String(), originalPieceID.String())
assert.Error(t, pieceid.UnmarshalJSON([]byte(`""`+originalPieceID.String()+`""`)))
assert.Error(t, pieceid.UnmarshalJSON([]byte(`{}`)))
}