Skip to content

Commit

Permalink
keyformat, internal: add fuzzers
Browse files Browse the repository at this point in the history
Adds fuzzers that have discovered some bugs, like:
* cosmos#760
* cosmos#761
  • Loading branch information
odeke-em committed May 4, 2023
1 parent 64ffc27 commit 4f5bb01
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
34 changes: 34 additions & 0 deletions internal/rand/fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package common

import (
mrand "math/rand"
"testing"
)

func TestRandStrHuge(t *testing.T) {
_ = RandStr(8455134228352958140)
}

func FuzzRandStr(f *testing.F) {
// 1. Seed the fuzzer with lengths.
mr := mrand.New(mrand.NewSource(10))
for i := 0; i < 100; i++ {
f.Add(mr.Int())
}

// 2. Now run the fuzzer.
rr := NewRand()
f.Fuzz(func(t *testing.T, n int) {
s := rr.Str(n)
// Ensure that we've got alphanumeric sequences entirely.
for _, c := range s {
switch {
case c >= '0' && c <= '9':
case c >= 'a' && c <= 'z':
case c >= 'A' && c <= 'Z':
default:
t.Fatalf("found a non-alphanumeric value %c in %q", c, s)
}
}
})
}
68 changes: 68 additions & 0 deletions keyformat/fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package keyformat

import (
"encoding/json"
"fmt"
"strings"
"testing"
)

func FuzzKeyFormatKeyBytes(f *testing.F) {
if testing.Short() {
f.Skip("in -short mode")
}

// 1. Create some seeds.
seeds := []*KeyFormat{
NewKeyFormat('a', 1, 2, 3, 5, 6, 0),
NewKeyFormat('b', 1, 2, 3, 5, 6, 1),
NewKeyFormat('b', 9, 21),
NewKeyFormat(byte('e'), 8, 8, 8),
NewKeyFormat(byte('e'), 8, 0),
}

type envelope struct {
KF *KeyFormat `json:"kf"`
BS [][]byte `json:"bs"`
}

for _, kf := range seeds {
bsL := [][][]byte{
[][]byte{[]byte(""), []byte("abcdefgh")},
[][]byte{{1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8, 9}},
[][]byte{{1, 2, 3, 4, 5, 6, 7, 8}, []byte("hellohello")},
[][]byte{{1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 1, 2, 2, 3, 3}},
}
for _, bs := range bsL {
blob, err := json.Marshal(&envelope{KF: kf, BS: bs})
if err != nil {
f.Fatal(err)
}
f.Add(blob)
}
}

// 2. Fuzz it now.
f.Fuzz(func(t *testing.T, inputJSON []byte) {
defer func() {
if r := recover(); r != nil {
str := fmt.Sprintf("%s", r)
if !strings.Contains(str, "provided to KeyFormat.KeyBytes() is longer than the") {
// Re-raise the panic as it panicked in an unexpected place.
panic(r)
}
}
}()

env := new(envelope)
if err := json.Unmarshal(inputJSON, env); err != nil {
return
}

kf := env.KF
if kf == nil {
return
}
_ = kf.KeyBytes(env.BS...)
})
}

0 comments on commit 4f5bb01

Please sign in to comment.