Merge pull request #175 from seaweedfs/test/decoder-fuzz-tests

test: Go native fuzz targets for the WAL, manifest and HEAD decoders
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-16 13:43:15 -08:00
commit eac2ff0587
4 files changed
+594

No files matched your search

@@ -0,0 +1,136 @@
package chunkstore
import (
"crypto/sha256"
"encoding/json"
"reflect"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// Fuzz targets for the persisted chunkstore documents: the manifest JSON
// reader (duplicate keys, nesting, trailing bytes) and the HEAD document.
// Under `go test` (no -fuzz) they run their seeds.
func fuzzHeadSeeds(tb testing.TB) [][]byte {
tb.Helper()
sum := sha256.Sum256([]byte("chunk"))
heads := []storage.ChunkHead{
{Gen: 1, Epoch: 2, Holder: "r1", RemoteLSN: 7, Chunks: map[uint64]storage.ChunkRef{0: {Key: "k0", SHA256: sum}, 5: {Key: "@v2/k5", SHA256: sum}}},
{Gen: 3, Epoch: 4, Holder: "r2", RemoteLSN: 9, State: storage.ChunkHeadDetached,
DetachedBy: &storage.ChunkDetachedBy{Holder: "r2", Epoch: 4, Gen: 3}, Chunks: map[uint64]storage.ChunkRef{}},
{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 3, ChunkBytes: 4 << 20, ManifestChunkCount: 2,
Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2}}},
}
var out [][]byte
for _, h := range heads {
e, err := headEntry(h)
if err != nil {
tb.Fatalf("seed %+v: %v", h, err)
}
out = append(out, e.Content)
}
return append(out,
[]byte(`{"format":1,"gen":1,"epoch":1,"holder":"a","remote_lsn":0,"gen":2}`), // duplicate key
[]byte(`{"format":1,"gen":1}{"x":1}`), // trailing value
[]byte(`{"format":2,"gen":1,"segments":{"0":{"Key":"","Owner":"v","Count":1}},"chunk_bytes":4096,"chunk_count":1}`),
[]byte(`[[[[[[[[[[1]]]]]]]]]]`), // nesting
[]byte(``),
)
}
// FuzzDecodeManifestJSON: never panics; when it accepts a document, the
// value equals what encoding/json alone decodes from the same bytes.
func FuzzDecodeManifestJSON(f *testing.F) {
for _, s := range fuzzHeadSeeds(f) {
f.Add(s)
}
f.Fuzz(func(t *testing.T, body []byte) {
var got any
if err := decodeManifestJSON(body, &got); err != nil {
return
}
var want any
if err := json.Unmarshal(body, &want); err != nil {
t.Fatalf("accepted a document encoding/json rejects: %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("decoded %v, encoding/json decodes %v", got, want)
}
})
}
// canonicalHead normalises the empty-collection forms the codec does not
// distinguish (an absent and an empty chunk map).
func canonicalHead(h storage.ChunkHead) storage.ChunkHead {
if len(h.Chunks) == 0 {
h.Chunks = nil
}
return h
}
// FuzzDecodeHeadDocument: never panics; a rejected document yields the zero
// head (no partial value); an accepted one re-encodes (headEntry) and
// decodes back to the same head, including through decodeHead with the
// entry's extended attributes.
func FuzzDecodeHeadDocument(f *testing.F) {
for _, s := range fuzzHeadSeeds(f) {
f.Add(s)
}
f.Fuzz(func(t *testing.T, body []byte) {
h, err := DecodeHeadDocument("fuzz", body)
if err != nil {
if gap := knownHeadDecodeGap(h, err); gap != "" {
return // pinned below
}
if !reflect.DeepEqual(h, storage.ChunkHead{}) {
t.Fatalf("error %v with a partial head %+v", err, h)
}
return
}
e, err := headEntry(h)
if err != nil {
if gap := knownHeadEncodeGap(h); gap != "" {
return
}
t.Fatalf("an accepted head does not re-encode: %v (%+v)", err, h)
}
again, err := decodeHead("fuzz", e)
if err != nil {
t.Fatalf("re-encoded head does not decode: %v", err)
}
if !reflect.DeepEqual(canonicalHead(again), canonicalHead(h)) {
t.Fatalf("head round trip: %+v, want %+v", again, h)
}
})
}
// knownHeadDecodeGap names the rejections that return a partial head:
// decodeHeadDoc returns the half-built segmented head when validateRoot
// fails (chunk_remote.go, "return h, err"). Found by FuzzDecodeHeadDocument;
// reported, not changed here: no caller reads the head on that error.
func knownHeadDecodeGap(h storage.ChunkHead, err error) string {
if err != nil && h.Segments != nil {
return "segmented head returned with a validateRoot error"
}
return ""
}
// knownHeadEncodeGap names accepted heads headEntry refuses (none known).
func knownHeadEncodeGap(storage.ChunkHead) string { return "" }
// Pins the known partial-value gap that knownHeadDecodeGap exempts: a
// segmented root whose segment reference is invalid is rejected, but the
// half-built head comes back with the error. If this starts failing, the
// gap is closed: drop knownHeadDecodeGap.
func TestDecodeHeadDocumentReturnsAPartialHeadOnAnInvalidRoot(t *testing.T) {
body := []byte(`{"format":2,"gen":1,"segments":{"0":{"Key":"","Owner":"v","Count":1}},"chunk_bytes":4096,"chunk_count":1}`)
h, err := DecodeHeadDocument("fuzz", body)
if err == nil {
t.Fatal("an invalid segment reference was accepted")
}
if h.Gen != 1 || h.Segments == nil {
t.Fatalf("expected the known partial head with the error, got %+v", h)
}
}
@@ -0,0 +1,131 @@
package parallelwal
import (
"bytes"
"encoding/binary"
"hash/crc32"
"reflect"
"testing"
)
var fuzzBlockSizes = []int{1, 16, 512, 4096}
func fuzzBlockSize(sel uint8) int { return fuzzBlockSizes[int(sel)%len(fuzzBlockSizes)] }
// FuzzParallelWALDecodeRecord: decodeRecord never panics; a rejected record
// is the zero value; an accepted one re-encodes to exactly its bytes (every
// header byte is a defined field).
func FuzzParallelWALDecodeRecord(f *testing.F) {
for _, bs := range fuzzBlockSizes {
rec := walRecord{LSN: 9, LBA: 2, Flags: flagWrite, Data: bytes.Repeat([]byte{0xA5}, bs)}
buf, err := encodeRecord(rec, bs)
if err != nil {
f.Fatal(err)
}
sel := uint8(0)
for i, v := range fuzzBlockSizes {
if v == bs {
sel = uint8(i)
}
}
f.Add(buf, sel)
torn := append([]byte(nil), buf...)
torn[len(torn)-1] ^= 1
f.Add(torn, sel)
}
f.Fuzz(func(t *testing.T, buf []byte, sel uint8) {
bs := fuzzBlockSize(sel)
rec, err := decodeRecord(buf, bs)
if err != nil {
if !reflect.DeepEqual(rec, walRecord{}) {
t.Fatalf("error %v with a partial record %+v", err, rec)
}
return
}
re, err := encodeRecord(rec, bs)
if err != nil {
t.Fatalf("re-encode of an accepted record: %v", err)
}
if !bytes.Equal(re, buf) {
t.Fatalf("accepted record does not re-encode to its bytes")
}
})
}
// FuzzParallelWALRecordRoundTrip: every record the encoder accepts decodes
// back to itself.
func FuzzParallelWALRecordRoundTrip(f *testing.F) {
f.Add(uint64(9), uint32(2), uint16(flagWrite), []byte("payload!"), uint8(1))
f.Fuzz(func(t *testing.T, lsn uint64, lba uint32, flags uint16, data []byte, sel uint8) {
bs := fuzzBlockSize(sel)
block := make([]byte, bs)
copy(block, data)
rec := walRecord{LSN: lsn, LBA: lba, Flags: flags, Data: block}
buf, err := encodeRecord(rec, bs)
if err != nil {
t.Fatalf("encode: %v", err)
}
got, err := decodeRecord(buf, bs)
if err != nil || !reflect.DeepEqual(got, rec) {
t.Fatalf("round trip: %+v err %v, want %+v", got, err, rec)
}
})
}
func seedHeader() fileHeader {
h := fileHeader{Generation: 3, CreatedAt: 1, BlockSize: 4096, NumBlocks: 64, LaneCount: 2, StripeBlocks: 8,
RecordSize: recordHeaderSize + 4096, SlotsPerLane: 32, DurableLSN: 10, CheckpointLSN: 4, WALTail: 2,
RetainPerLane: 4, ActiveExtent: 1}
h.LaneHeads[0], h.LaneTails[0] = 5, 1
h.LaneHeads[1], h.LaneTails[1] = 6, 2
return h
}
// headerFromFuzz builds a 4096-byte header slot from fuzz bytes with a valid
// magic, version, size and CRC, so the fuzzer exercises field validation.
func headerFromFuzz(data []byte) []byte {
buf := make([]byte, headerSize)
copy(buf, data)
copy(buf[0:4], headerMagic)
binary.LittleEndian.PutUint16(buf[4:6], headerVersion)
binary.LittleEndian.PutUint16(buf[6:8], headerSize)
binary.LittleEndian.PutUint32(buf[headerCRCOffset:], crc32.ChecksumIEEE(buf[:headerCRCOffset]))
return buf
}
// FuzzParallelWALDecodeHeader: decodeHeader never panics on any bytes; on a
// CRC-valid slot a rejection is the zero header, and an accepted header is
// valid and survives an encode/decode round trip unchanged.
func FuzzParallelWALDecodeHeader(f *testing.F) {
good, err := encodeHeader(seedHeader())
if err != nil {
f.Fatal(err)
}
f.Add(good[:], false)
f.Add(good[:100], true)
f.Add([]byte{}, true)
f.Fuzz(func(t *testing.T, data []byte, fixup bool) {
buf := data
if fixup {
buf = headerFromFuzz(data)
}
h, err := decodeHeader(buf)
if err != nil {
if !reflect.DeepEqual(h, fileHeader{}) {
t.Fatalf("error %v with a partial header", err)
}
return
}
if err := h.validate(); err != nil {
t.Fatalf("accepted header is invalid: %v", err)
}
re, err := encodeHeader(h)
if err != nil {
t.Fatalf("re-encode of an accepted header: %v", err)
}
got, err := decodeHeader(re[:])
if err != nil || !reflect.DeepEqual(got, h) {
t.Fatalf("header round trip: %+v err %v", got, err)
}
})
}
@@ -0,0 +1,96 @@
package smartwal
import (
"bytes"
"encoding/binary"
"hash/crc32"
"testing"
)
// FuzzSmartWALDecode: decode never panics; a rejected slot yields the zero
// record; an accepted slot re-encodes to the same record and to the same
// bytes outside the reserved fields.
func FuzzSmartWALDecode(f *testing.F) {
good := encode(record{LSN: 7, LBA: 3, Flags: flagWrite, DataCRC32: 0xDEADBEEF})
f.Add(good[:])
f.Add(make([]byte, recordSize))
f.Add(good[:recordSize-1])
torn := good
torn[9] ^= 1
f.Add(torn[:])
f.Fuzz(func(t *testing.T, buf []byte) {
r, ok := decode(buf)
if !ok {
if r != (record{}) {
t.Fatalf("rejected slot with a partial record %+v", r)
}
return
}
re := encode(r)
if got, ok := decode(re[:]); !ok || got != r {
t.Fatalf("re-encode of %+v decodes to %+v (ok %t)", r, got, ok)
}
if gap := knownSmartWALDecodeGap(buf); gap != "" {
return // pinned below
}
if !bytes.Equal(re[:], buf[:recordSize]) {
t.Fatalf("accepted slot does not re-encode to its bytes: %x vs %x", re, buf[:recordSize])
}
})
}
// FuzzSmartWALRecordFields: slots with a valid magic and record CRC but
// arbitrary fields, including the reserved bytes.
func FuzzSmartWALRecordFields(f *testing.F) {
f.Add(uint8(flagWrite), uint32(3), uint64(7), uint32(0xDEADBEEF), uint16(0), uint64(0))
f.Add(uint8(flagTrim), uint32(0), uint64(1), uint32(0), uint16(1), uint64(9))
f.Fuzz(func(t *testing.T, flags uint8, lba uint32, lsn uint64, dataCRC uint32, res1 uint16, res2 uint64) {
var buf [recordSize]byte
buf[0] = recordMagic
buf[1] = flags
binary.LittleEndian.PutUint16(buf[2:4], res1)
binary.LittleEndian.PutUint32(buf[4:8], lba)
binary.LittleEndian.PutUint64(buf[8:16], lsn)
binary.LittleEndian.PutUint64(buf[16:24], res2)
binary.LittleEndian.PutUint32(buf[24:28], dataCRC)
binary.LittleEndian.PutUint32(buf[28:32], crc32.ChecksumIEEE(buf[:28]))
r, ok := decode(buf[:])
if !ok {
t.Fatalf("a slot with a valid magic and CRC was rejected")
}
if r != (record{LSN: lsn, LBA: lba, Flags: flags, DataCRC32: dataCRC}) {
t.Fatalf("decoded %+v", r)
}
if gap := knownSmartWALDecodeGap(buf[:]); gap == "" {
re := encode(r)
if re != buf {
t.Fatalf("canonical slot does not re-encode to its bytes")
}
}
})
}
// FuzzSmartWALRoundTrip: every record encodes and decodes back to itself.
func FuzzSmartWALRoundTrip(f *testing.F) {
f.Add(uint64(7), uint32(3), uint8(flagWrite), uint32(0xDEADBEEF))
f.Fuzz(func(t *testing.T, lsn uint64, lba uint32, flags uint8, dataCRC uint32) {
r := record{LSN: lsn, LBA: lba, Flags: flags, DataCRC32: dataCRC}
buf := encode(r)
got, ok := decode(buf[:])
if !ok || got != r {
t.Fatalf("round trip of %+v: %+v (ok %t)", r, got, ok)
}
})
}
// knownSmartWALDecodeGap names accepted slots that are not canonical:
// non-zero reserved bytes (2:4, 16:24) are covered by the record CRC but
// ignored, so such a slot is accepted although encode never writes it.
// Found by FuzzSmartWALRecordFields; reported, not changed here. Any flag
// value is accepted too (decode does not check flags).
func knownSmartWALDecodeGap(buf []byte) string {
if binary.LittleEndian.Uint16(buf[2:4]) != 0 || binary.LittleEndian.Uint64(buf[16:24]) != 0 {
return "non-zero reserved bytes"
}
return ""
}
@@ -0,0 +1,231 @@
package storage
import (
"bytes"
"encoding/binary"
"hash/crc32"
"reflect"
"testing"
)
// walEntryFuzzSeeds are well-formed records of every kind the writers
// produce, plus truncated and corrupted variants. Under `go test` (no
// -fuzz) the fuzz targets below run exactly these seeds.
func walEntryFuzzSeeds(t testing.TB) [][]byte {
t.Helper()
enc := func(e walEntry) []byte {
b, err := e.encode()
if err != nil {
t.Fatalf("seed %+v: %v", e, err)
}
return b
}
pad, err := encodeWALPadding(walEntryHeaderSize + 16)
if err != nil {
t.Fatal(err)
}
block := bytes.Repeat([]byte{0xA5}, 512)
seeds := [][]byte{
enc(walEntry{LSN: 1, Type: walEntryWrite, LBA: 7, Length: uint32(len(block)), Data: block}),
enc(walEntry{LSN: 9, Reserved: 2, Type: walEntryWriteBatch, LBA: 3, Length: 1024, Data: bytes.Repeat([]byte{0x5A}, 1024)}),
enc(walEntry{LSN: 4, Type: walEntryTrim, LBA: 10, Length: 8192}),
enc(walEntry{LSN: 5, Type: walEntryBarrier}),
pad,
{},
make([]byte, walEntryHeaderSize),
}
good := seeds[0]
seeds = append(seeds,
good[:walEntryHeaderSize-1], // short header
good[:len(good)-1], // short trailer
append(append([]byte{}, good...), 0xFF), // trailing byte
)
flipped := append([]byte{}, good...)
flipped[40] ^= 0x01 // data byte: CRC mismatch
seeds = append(seeds, flipped)
huge := append([]byte{}, good[:walEntryHeaderSize]...)
binary.LittleEndian.PutUint32(huge[26:], ^uint32(0)) // Length claims 4 GiB
seeds = append(seeds, huge)
return seeds
}
// FuzzDecodeWALEntry: decodeWALEntry never panics; an error comes with the
// zero value; an accepted record is self-consistent and re-encodes to
// exactly the bytes it was decoded from.
func FuzzDecodeWALEntry(f *testing.F) {
for _, s := range walEntryFuzzSeeds(f) {
f.Add(s)
}
f.Fuzz(func(t *testing.T, data []byte) {
e, err := decodeWALEntry(data)
if err != nil {
if !reflect.DeepEqual(e, walEntry{}) {
t.Fatalf("error %v with a partial value %+v", err, e)
}
return
}
size := walEntryHeaderSize + len(e.Data)
if size > len(data) {
t.Fatalf("decoded %d bytes from a %d-byte buffer", size, len(data))
}
if got := binary.LittleEndian.Uint32(data[size-4:]); got != uint32(size) {
t.Fatalf("EntrySize field %d, record is %d bytes", got, size)
}
switch e.Type {
case walEntryWrite, walEntryWriteBatch, walEntryPadding:
if uint32(len(e.Data)) != e.Length {
t.Fatalf("type %d: %d data bytes, Length %d", e.Type, len(e.Data), e.Length)
}
default:
if e.Data != nil {
t.Fatalf("type %d decoded with a payload", e.Type)
}
}
if gap := knownWALDecodeGap(e); gap != "" {
return // pinned below; see knownWALDecodeGap
}
if reason := walEntryEncoderRefuses(e); reason != "" {
t.Fatalf("decoder accepted a record the encoder refuses (%s): %+v", reason, e)
}
re, err := e.encode()
if err != nil {
t.Fatalf("re-encode of an accepted record: %v", err)
}
if !bytes.Equal(re, data[:size]) {
t.Fatalf("re-encode differs from the decoded bytes")
}
})
}
// FuzzWALEntryRoundTrip: every entry the encoder accepts decodes back to
// itself.
func FuzzWALEntryRoundTrip(f *testing.F) {
f.Add(uint64(1), uint64(0), uint8(walEntryWrite), uint8(0), uint64(7), uint32(4), []byte("abcd"))
f.Add(uint64(9), uint64(2), uint8(walEntryWriteBatch), uint8(0), uint64(3), uint32(2), []byte("xy"))
f.Add(uint64(4), uint64(0), uint8(walEntryTrim), uint8(0), uint64(10), uint32(8192), []byte(nil))
f.Add(uint64(5), uint64(0), uint8(walEntryBarrier), uint8(0), uint64(0), uint32(0), []byte(nil))
f.Add(uint64(6), uint64(0), uint8(walEntryPadding), uint8(0), uint64(0), uint32(3), []byte{0, 0, 0})
f.Fuzz(func(t *testing.T, lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, data []byte) {
e := walEntry{LSN: lsn, Reserved: reserved, Type: typ, Flags: flags, LBA: lba, Length: length, Data: data}
if len(e.Data) == 0 {
e.Data = nil
}
buf, err := e.encode()
if err != nil {
return
}
if gap := knownWALEncodeGap(e); gap != "" {
return // pinned below; see knownWALEncodeGap
}
got, err := decodeWALEntry(buf)
if err != nil {
t.Fatalf("encoder accepted %+v but its bytes do not decode: %v", e, err)
}
if !reflect.DeepEqual(got, e) {
t.Fatalf("round trip: got %+v, want %+v", got, e)
}
})
}
// walEntryEncoderRefuses mirrors encodedSize's checks for a decoded entry
// ("" when the encoder accepts it).
func walEntryEncoderRefuses(e walEntry) string {
if _, err := e.encodedSize(); err != nil {
return err.Error()
}
return ""
}
// rawWALEntry lays out header fields, payload and a valid CRC/EntrySize
// exactly as the on-disk format does, without the encoder's checks, so the
// fuzzer reaches the decoder's acceptance rules instead of the CRC.
func rawWALEntry(lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, payload []byte) []byte {
le := binary.LittleEndian
buf := make([]byte, 30+len(payload)+8)
le.PutUint64(buf[0:], lsn)
le.PutUint64(buf[8:], reserved)
buf[16] = typ
buf[17] = flags
le.PutUint64(buf[18:], lba)
le.PutUint32(buf[26:], length)
copy(buf[30:], payload)
end := 30 + len(payload)
le.PutUint32(buf[end:], crc32.ChecksumIEEE(buf[:end]))
le.PutUint32(buf[end+4:], uint32(len(buf)))
return buf
}
// FuzzDecodeWALEntryFields: records with a valid CRC and EntrySize but
// arbitrary field values; the decoder must accept only what the encoder
// can produce.
func FuzzDecodeWALEntryFields(f *testing.F) {
f.Add(uint64(1), uint64(0), uint8(walEntryWrite), uint8(0), uint64(7), uint32(4), []byte("abcd"))
f.Add(uint64(9), uint64(2), uint8(walEntryWriteBatch), uint8(0), uint64(3), uint32(2), []byte("xy"))
f.Add(uint64(4), uint64(0), uint8(walEntryTrim), uint8(0), uint64(10), uint32(8192), []byte(nil))
f.Add(uint64(5), uint64(0), uint8(walEntryBarrier), uint8(0), uint64(0), uint32(0), []byte(nil))
f.Add(uint64(6), uint64(0), uint8(walEntryPadding), uint8(0), uint64(0), uint32(3), []byte{0, 0, 0})
f.Fuzz(func(t *testing.T, lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, payload []byte) {
buf := rawWALEntry(lsn, reserved, typ, flags, lba, length, payload)
e, err := decodeWALEntry(buf)
if err != nil {
if !reflect.DeepEqual(e, walEntry{}) {
t.Fatalf("error %v with a partial value %+v", err, e)
}
return
}
if gap := knownWALDecodeGap(e); gap != "" {
return // pinned below; see knownWALDecodeGap
}
if reason := walEntryEncoderRefuses(e); reason != "" {
t.Fatalf("decoder accepted a record the encoder refuses (%s): %+v", reason, e)
}
re, err := e.encode()
if err != nil || !bytes.Equal(re, buf[:walEntryHeaderSize+len(e.Data)]) {
t.Fatalf("accepted record does not re-encode to its bytes (err %v): %+v", err, e)
}
})
}
// knownWALDecodeGap names the record shapes decodeWALEntry accepts although
// the encoder never produces them (found by FuzzDecodeWALEntryFields;
// reported, not fixed here). Recovery already fails closed on an invalid
// batch (WALIntegrity), so a decoder-level rejection is not a drop-in
// change: it would turn that into a torn-entry stop. Any shape not listed
// here fails the fuzz targets.
func knownWALDecodeGap(e walEntry) string {
switch e.Type {
case walEntryWrite:
if e.Length == 0 {
return "write with no data"
}
case walEntryWriteBatch:
if e.Reserved == 0 || e.Length == 0 {
return "batch shape (checked by recovery, not by the decoder)"
}
case walEntryBarrier:
if e.Length != 0 {
return "barrier with a non-zero Length"
}
case walEntryTrim, walEntryPadding:
default:
return "unknown entry type"
}
return ""
}
// knownWALEncodeGap names the entries walEntry.encode accepts but whose
// bytes do not decode back (found by FuzzWALEntryRoundTrip; no writer
// builds them).
func knownWALEncodeGap(e walEntry) string {
switch e.Type {
case walEntryWrite, walEntryWriteBatch, walEntryTrim, walEntryBarrier:
return ""
case walEntryPadding:
if uint32(len(e.Data)) != e.Length {
return "padding whose Length differs from its payload"
}
return ""
default:
return "unknown entry type"
}
}