Add generalized decodeJsonByteString and a fuzz target for it

This commit is contained in:
Matt Joiner 2021-12-11 13:43:25 +11:00
parent 14ee69aaeb
commit 1d787c3923
5 changed files with 52 additions and 5 deletions

31
webtorrent/fuzz_test.go Normal file
View File

@ -0,0 +1,31 @@
//go:build go1.18
// +build go1.18
package webtorrent
import (
"encoding/json"
"testing"
qt "github.com/frankban/quicktest"
)
func FuzzJsonBinaryStrings(f *testing.F) {
f.Fuzz(func(t *testing.T, in []byte) {
jsonBytes, err := json.Marshal(binaryToJsonString(in))
if err != nil {
t.Fatal(err)
}
// t.Logf("%q", jsonBytes)
var jsonStr string
err = json.Unmarshal(jsonBytes, &jsonStr)
if err != nil {
t.Fatal(err)
}
// t.Logf("%q", jsonStr)
c := qt.New(t)
out, err := decodeJsonByteString(jsonStr, []byte{})
c.Assert(err, qt.IsNil)
c.Assert(out, qt.DeepEquals, in)
})
}

View File

@ -0,0 +1,2 @@
go test fuzz v1
[]byte("\x93")

View File

@ -0,0 +1,2 @@
go test fuzz v1
[]byte("0")

View File

@ -0,0 +1,2 @@
go test fuzz v1
[]byte("")

View File

@ -48,6 +48,17 @@ func binaryToJsonString(b []byte) string {
}
func jsonStringToInfoHash(s string) (ih [20]byte, err error) {
b, err := decodeJsonByteString(s, ih[:0])
if err != nil {
return
}
if len(b) != len(ih) {
err = fmt.Errorf("string decoded to %v bytes", len(b))
}
return
}
func decodeJsonByteString(s string, b []byte) ([]byte, error) {
defer func() {
r := recover()
if r == nil {
@ -55,12 +66,11 @@ func jsonStringToInfoHash(s string) (ih [20]byte, err error) {
}
panic(fmt.Sprintf("%q", s))
}()
for i, c := range []rune(s) {
for _, c := range []rune(s) {
if c < 0 || c > math.MaxUint8 {
err = fmt.Errorf("bad infohash string: %v", s)
return
return b, fmt.Errorf("rune out of bounds: %v", c)
}
ih[i] = byte(c)
b = append(b, byte(c))
}
return
return b, nil
}