Tur Dokumentasi Blog Coba

Proposal: Custom Fuzz Input Types

Author: Richard Hansen rhansen@rhansen.org

Last updated: 2023-06-08

Discussion at https://go.dev/issue/48815.

Abstract

Extend testing.F.Fuzz to support custom types, with their own custom mutation logic, as input parameters. This enables developers to perform structure-aware fuzzing.

Background

As of Go 1.20, testing.F.Fuzz only accepts fuzz functions that have basic parameter types: []byte, string, int, etc. Custom input types with custom mutation logic would make it easier to fuzz functions that take complex data structures as input.

It is technically possible to fuzz such functions using the basic types, but the benefit is limited:

See Structure-Aware Fuzzing with libFuzzer for additional background.

Proposal

Extend testing.F.Fuzz to accept fuzz functions with parameter types that implement the following interface (not exported, just documented in testing.F.Fuzz):

// A customMutator is a fuzz input value that is self-mutating. This interface
// extends the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
// interfaces.
type customMutator interface {
	// MarshalBinary encodes the customMutator's value in a platform-independent
	// way (e.g., JSON or Protocol Buffers).
	MarshalBinary() ([]byte, error)
	// UnmarshalBinary restores the customMutator's value from encoded data
	// previously returned from a call to MarshalBinary.
	UnmarshalBinary([]byte) error
	// Mutate pseudo-randomly transforms the customMutator's value. The mutation
	// must be repeatable: every call to Mutate with the same starting value and
	// seed must result in the same transformed value.
	Mutate(ctx context.Context, seed int64) error
}

Also extend the seed corpus file format to support custom values. A line for a custom value has the following form:

custom("type identifier here", []byte("marshal output here"))

The type identifier is a globally unique and stable identifier derived from the value's fully qualified type name, such as "*example.com/mod/pkg.myType".

Example Usage

package pkg_test

import (
	"encoding/json"
	"testing"

	"github.com/go-loremipsum/loremipsum"
)

type fuzzInput struct{ Word string }

func (v *fuzzInput) MarshalBinary() ([]byte, error) { return json.Marshal(v) }
func (v *fuzzInput) UnmarshalBinary(d []byte) error { return json.Unmarshal(d, v) }
func (v *fuzzInput) Mutate(ctx context.Context, seed int64) error {
	v.Word = loremipsum.NewWithSeed(seed).Word()
	return nil
}

func FuzzInput(f *testing.F) {
	f.Fuzz(func(t *testing.T, v *fuzzInput) {
		if v.Word == "lorem" {
			t.Fatal("boom!")
		}
	})
}

The fuzzer eventually encounters an input value that causes the test function to fail, and produces a seed corpus file in testdata/fuzz like the following:

go test fuzz v1
custom("*example.com/mod/pkg_test.fuzzInput", []byte("{\"Word\":\"lorem\"}"))

Rationale

Private interface

The customMutator interface is not exported for a few reasons:

MarshalBinary, UnmarshalBinary methods

Marshal and Unmarshal would be shorter to type than MarshalBinary and UnmarshalBinary, but the longer names make it easier to extend existing types that already implement the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler interfaces.

MarshalText and UnmarshalText were considered but rejected because the most natural representation of a custom type might be binary, not text.

UnmarshalBinary is used both to load seed corpus files from disk and to transmit input values between the coordinator and its workers. Unmarshaling malformed data from disk is allowed to fail, but unmarshaling after transmission to another process is expected to always succeed.

MarshalBinary is used both to save seed corpus files to disk and to transmit input values between the coordinator and its workers. Marshaling is expected to always succeed. Despite this, it returns an error for several reasons:

Panicking is especially problematic because:

Mutate method

The seed parameter is an int64, not an unsigned integer type as is common for holding random bits, because that is what math/rand.NewSource takes.

The Mutate method must be repeatable to avoid violating an assumption in the coordinator–worker protocol. This may be relaxed in the future by revising the protocol.

Some alternatives for the Mutate method were considered:

Because mutation operations on custom types are expected to be somewhat complex (otherwise a basic type would probably suffice), the Mutate(ctx context.Context, seed int64) error option is believed to be the best choice.

Minimization

To simplify the initial implementation, input types are not minimizable. Minimizability could be added in the future by accepting a type like the following and calling its Minimize method:

// A customMinimizingMutator is a customMutator that supports attempts to reduce
// the size of an interesting value.
type customMinimizingMutator interface {
	customMutator
	// Minimize attempts to produce the smallest value (usually defined as
	// easiest to process by machine and/or humans) that still provides the same
	// coverage as the original value. It repeatedly generates candidates,
	// checking each one for suitability with the given callback. It returns
	// a suitable candidate if it is satisfied that the candidate is
	// sufficiently small or nil if it has given up searching.
	Minimize(seed int64, check func(candidate any) (bool, error)) (any, error)
}

Compatibility

No changes in behavior are expected with existing code and seed corpus files.

Implementation

See https://go.dev/cl/493304 for an initial attempt.

For the initial implementation, a worker can simply panic if one of the custom type's methods returns an error. A future change can improve UX by plumbing the error.

No particular Go release is targeted.