istio.io/istio@v0.0.0-20240520182934-d79c90f27776/tests/fuzz/compare_fuzzer.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // nolint: revive
    16  package fuzz
    17  
    18  import (
    19  	"bytes"
    20  	"errors"
    21  
    22  	fuzz "github.com/AdaLogics/go-fuzz-headers"
    23  
    24  	"istio.io/istio/istioctl/pkg/writer/compare"
    25  )
    26  
    27  func createIstiodDumps(f *fuzz.ConsumeFuzzer) (map[string][]byte, error) {
    28  	m := make(map[string][]byte)
    29  	maxNoEntries := 50
    30  	qty, err := f.GetInt()
    31  	if err != nil {
    32  		return m, err
    33  	}
    34  	noOfEntries := qty % maxNoEntries
    35  	if noOfEntries == 0 {
    36  		return m, errors.New("a map of zero-length was created")
    37  	}
    38  	for i := 0; i < noOfEntries; i++ {
    39  		k, err := f.GetString()
    40  		if err != nil {
    41  			return m, err
    42  		}
    43  		v, err := f.GetBytes()
    44  		if err != nil {
    45  			return m, err
    46  		}
    47  		m[k] = v
    48  	}
    49  	return m, nil
    50  }
    51  
    52  func FuzzCompareDiff(data []byte) int {
    53  	f := fuzz.NewConsumer(data)
    54  	istiodDumps, err := createIstiodDumps(f)
    55  	if err != nil {
    56  		return 0
    57  	}
    58  	envoyDump, err := f.GetBytes()
    59  	if err != nil {
    60  		return 0
    61  	}
    62  	var buf bytes.Buffer
    63  	c, err := compare.NewComparator(&buf, istiodDumps, envoyDump)
    64  	if err != nil {
    65  		return 0
    66  	}
    67  	_ = c.Diff()
    68  	return 1
    69  }