Fix Uint256 Json Parsing (#12540)

* add stronger checks

* radek's review
This commit is contained in:
Nishant Das 2023-06-16 17:43:20 +08:00 committed by GitHub
parent 6edbfa3128
commit 63d81144e9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 18 additions and 8 deletions

View File

@ -135,15 +135,14 @@ func (s Uint256) SSZBytes() []byte {
// UnmarshalJSON takes in a byte array and unmarshals the value in Uint256
func (s *Uint256) UnmarshalJSON(t []byte) error {
start := 0
end := len(t)
if t[0] == '"' {
start += 1
if len(t) < 2 {
return errors.Errorf("provided Uint256 json string is too short: %s", string(t))
}
if t[end-1] == '"' {
end -= 1
if t[0] != '"' || t[end-1] != '"' {
return errors.Errorf("provided Uint256 json string is malformed: %s", string(t))
}
return s.UnmarshalText(t[start:end])
return s.UnmarshalText(t[1 : end-1])
}
// UnmarshalText takes in a byte array and unmarshals the text in Uint256

View File

@ -1156,6 +1156,14 @@ func TestUint256Unmarshal(t *testing.T) {
require.Equal(t, expected, string(m))
}
func TestUint256Unmarshal_BadData(t *testing.T) {
var bigNum Uint256
assert.ErrorContains(t, "provided Uint256 json string is too short", bigNum.UnmarshalJSON([]byte{'"'}))
assert.ErrorContains(t, "provided Uint256 json string is malformed", bigNum.UnmarshalJSON([]byte{'"', '1', '2'}))
}
func TestUint256UnmarshalNegative(t *testing.T) {
m := "-1"
var value Uint256

View File

@ -18,6 +18,9 @@ func (p *EpochParticipation) UnmarshalJSON(b []byte) error {
if len(b) < 2 {
return errors.New("epoch participation length must be at least 2")
}
if b[0] != '"' || b[len(b)-1] != '"' {
return errors.Errorf("provided epoch participation json string is malformed: %s", string(b))
}
// Remove leading and trailing quotation marks.
jsonString := string(b)

View File

@ -23,7 +23,7 @@ func TestUnmarshalEpochParticipation(t *testing.T) {
ep := EpochParticipation{}
err := ep.UnmarshalJSON([]byte(":illegal:"))
require.NotNil(t, err)
assert.ErrorContains(t, "could not decode epoch participation base64 value", err)
assert.ErrorContains(t, "provided epoch participation json string is malformed", err)
})
t.Run("length too small", func(t *testing.T) {
ep := EpochParticipation{}
@ -38,6 +38,6 @@ func TestUnmarshalEpochParticipation(t *testing.T) {
})
t.Run("invalid value", func(t *testing.T) {
ep := EpochParticipation{}
require.ErrorContains(t, "could not decode epoch participation base64 value", ep.UnmarshalJSON([]byte("XdHJ1ZQ==X")))
require.ErrorContains(t, "provided epoch participation json string is malformed", ep.UnmarshalJSON([]byte("XdHJ1ZQ==X")))
})
}