diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1162852c..7065594b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,34 @@ env: GITHUB_TOKEN: ${{ github.token }} jobs: + # What the machine parses from outside, a checkpoint's record and QMP's replies, fuzzed for a + # minute a target (task fuzz, #653). An input that fails is kept as the run's artifact: commit + # it under the package's testdata/fuzz with the fix, and go test runs it from then on. + fuzz: + name: Fuzz + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + cache: true + + - name: Fuzz each target + run: go tool task fuzz + + - name: Keep the failing inputs + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fuzz-failures + path: "**/testdata/fuzz/" + if-no-files-found: ignore + gate: # The check main's ruleset requires, named Gate in every spin-stack repository. name: Gate diff --git a/Taskfile.yml b/Taskfile.yml index d997a75f..80da0457 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -155,6 +155,27 @@ tasks: fi - coverfloor {{.COVERAGE_FLOOR}} coverage.out + fuzz: + desc: >- + Each Go fuzz target (func FuzzX: what the machine parses from outside, a checkpoint's record + and QMP's replies, #653) for FUZZTIME (default 60s) each. A failing input is written to the + package's testdata/fuzz, where go test runs it from then on: commit it with the fix. + vars: + FUZZTIME: '{{.FUZZTIME | default "60s"}}' + env: + SPIN_MACHINE_OUTPUT: /nonexistent + cmds: + # The targets are found, not listed: a list is how one goes missing. Minimizing an input + # that adds coverage takes up to a minute by default, which a bounded run spends idle. + - | + set -eu + go test -list '^Fuzz' ./... | awk '/^Fuzz/ { t[n++] = $1 } /^ok / { for (i = 0; i < n; i++) print $2, t[i]; n = 0 }' > "${TMPDIR:-/tmp}/fuzz-targets" + [ -s "${TMPDIR:-/tmp}/fuzz-targets" ] || { echo "no fuzz targets found" >&2; exit 1; } + while read -r pkg target; do + echo "== $pkg $target" + go test -run '^$' -fuzz "^$target\$" -fuzztime {{.FUZZTIME}} -fuzzminimizetime 5s "$pkg" + done < "${TMPDIR:-/tmp}/fuzz-targets" + lint: desc: >- Everything CI checks that is not a build: formatting, vet, the Taskfiles parse, every diff --git a/docs/cli.md b/docs/cli.md index c56dff04..3aa066c1 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -162,7 +162,9 @@ the release that needed them. What a person types is spin-machine-dev. The Taskfile is go-tools' gates, the same in every spin-stack repository (`test`, `lint`, `mutate`, `coverage`), and CI's plumbing: -`bin`, `git:app` (git as the release app), `trace` and `ship-it:wake`. The probes' targets +`bin`, `git:app` (git as the release app), `trace` and `ship-it:wake`. `fuzz` runs each Go fuzz target +(`func FuzzX`: a checkpoint's record and QMP's replies) for `FUZZTIME` each, as ci.yml's `fuzz` +job does; an input one fails on is committed under the package's `testdata/fuzz` with the fix. The probes' targets (`boot:*`), `lab`, `lab:ci` and `vsock` run what the verbs built. `versions`, `bump`, `release`, `lint:workflows` and `consumers` are not written here: the diff --git a/gates/attest_test.go b/gates/attest_test.go index fab81ad3..9b5ccda9 100644 --- a/gates/attest_test.go +++ b/gates/attest_test.go @@ -21,6 +21,7 @@ func TestEveryUploadIsAttested(t *testing.T) { UploadTasks: []string{"spin-machine-dev publish qemu", "spin-machine-dev refresh builders"}, AttestTasks: []string{"spin-machine-dev release sign"}, NotPublished: map[string]string{ + "ci.yml/fuzz/Keep the failing inputs": "the inputs a fuzz target failed on, for a person to commit with the fix", "ci.yml/gate/Upload Go coverage HTML": "a coverage page for a person, kept seven days", "codeql.yml/analyze/Keep upstream's results in the touched files": "upstream's analysis results, for a person to read; nothing installs or verifies them", "codeql.yml/analyze/Keep the SARIF": "a failed scope's SARIF, for a person to read why; nothing installs or verifies it", diff --git a/machine/fuzz_test.go b/machine/fuzz_test.go new file mode 100644 index 00000000..597dc844 --- /dev/null +++ b/machine/fuzz_test.go @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: Apache-2.0 + +package machine + +import ( + "encoding/json" + "errors" + "maps" + "slices" + "testing" +) + +// What a checkpoint's caller hands back to Resume is bytes it kept beside a state file, stored +// and copied by spin and read here (#653). These fuzz targets hold what Saved, its record and +// CanResume promise of any bytes that read as one. `task fuzz` runs each for a bounded time, and +// a failing input it finds lands in testdata/fuzz, where go test runs it from then on. + +// savedSeeds are records of the shapes CanResume's tests use: spin's machine, one from before +// the vCPU's properties were held, one with vCPUs and disks added, and an empty one. +func savedSeeds(f *testing.F) [][]byte { + f.Helper() + spin := target(f, nil) + old := target(f, func(t *Target, _ facts) { t.CPU.Properties = nil }) + added := json.RawMessage(`{"cpus":[{"id":"cpu-1","driver":"host-x86_64-cpu","props":{"socket-id":1,"core-id":0,"thread-id":0}}],"disks":[{"serial":"ext","target":3}]}`) + var seeds [][]byte + for _, s := range []Saved{ + {Format: FormatMappedRAM, From: spin, Length: 1 << 30}, + {Format: FormatStream, From: old}, + {Format: FormatMappedRAM, From: spin, Added: added}, + {}, + } { + b, err := json.Marshal(s) + if err != nil { + f.Fatal(err) + } + seeds = append(seeds, b) + } + return seeds +} + +// Any bytes that read as a Saved write one form, read back to the same record, and resume into +// the machine they were taken on exactly when that machine reads their format and names a VMM +// with a version: a record never refuses itself for anything else, and never with an error +// that is not a Refusal. What it says it added again is a vCPU in a slot or refused. +func FuzzARecordReadBack(f *testing.F) { + for _, s := range savedSeeds(f) { + f.Add(s) + } + f.Fuzz(func(t *testing.T, b []byte) { + var saved Saved + if json.Unmarshal(b, &saved) != nil { + return + } + first, err := json.Marshal(saved) + if err != nil { + t.Fatalf("a Saved read from %q does not write: %v", b, err) + } + var back Saved + if err := json.Unmarshal(first, &back); err != nil { + t.Fatalf("a Saved written as %s does not read back: %v", first, err) + } + if second, _ := json.Marshal(back); string(second) != string(first) { + t.Fatalf("a Saved read back writes another form:\n%s\n%s", first, second) + } + + err = CanResume(saved, saved.From) + refusal(t, err) + _, _, versioned := vmmVersion(saved.From.VMM) + if itself := slices.Contains(saved.From.Formats, saved.Format) && versioned; itself != (err == nil) { + t.Fatalf("a record resumed into its own machine: %v, want refused only for its format or VMM\n%s", err, first) + } + if again := CanResume(back, back.From); errString(again) != errString(err) { + t.Fatalf("read back, the record resumes into itself with %v, and before with %v", again, err) + } + + var again added + if len(saved.Added) == 0 || json.Unmarshal(saved.Added, &again) != nil { + return + } + allowed := append([]string{"driver", "id"}, cpuTopology...) + for _, c := range again.CPUs { + args, err := c.deviceArgs() + if err != nil { + continue + } + for k := range maps.Keys(args) { + if !slices.Contains(allowed, k) { + t.Fatalf("vCPU %q is added again with %s, which names no slot", c.ID, k) + } + } + } + }) +} + +// Any two records that read: CanResume answers nil or a Refusal naming each difference, and nil +// only for a machine that reads the checkpoint's format. +func FuzzCanResume(f *testing.F) { + seeds := savedSeeds(f) + for _, s := range seeds { + for _, h := range seeds { + f.Add(s, h) + } + } + f.Fuzz(func(t *testing.T, s, h []byte) { + var saved, here Saved + if json.Unmarshal(s, &saved) != nil || json.Unmarshal(h, &here) != nil { + return + } + err := CanResume(saved, here.From) + refusal(t, err) + if err == nil && !slices.Contains(here.From.Formats, saved.Format) { + t.Fatalf("a checkpoint of format %q resumes into a machine that reads %q", saved.Format, here.From.Formats) + } + }) +} + +// refusal fails t unless err is nil or a Refusal whose every difference names a part and a rule. +func refusal(t *testing.T, err error) { + t.Helper() + if err == nil { + return + } + var r *Refusal + if !errors.As(err, &r) || len(r.Differences) == 0 { + t.Fatalf("CanResume = %v, want nil or a Refusal naming a difference", err) + } + for _, d := range r.Differences { + if d.Part == "" || d.Rule == "" { + t.Fatalf("a difference names no part or no rule: %+v", d) + } + } +} + +func errString(err error) string { + if err == nil { + return "" + } + return err.Error() +} diff --git a/machine/record.go b/machine/record.go index f2481d62..5917d139 100644 --- a/machine/record.go +++ b/machine/record.go @@ -5,6 +5,7 @@ package machine import ( "cmp" "encoding/json" + "errors" "fmt" "slices" "strconv" @@ -63,7 +64,8 @@ type count struct { } // newHardware sorts both lists by name, and refuses a name given twice or given in both lists: a -// fact has one value and one rule. +// fact has one value and one rule. It refuses an empty name too: a difference in a fact with none +// would name nothing (FuzzCanResume, #653). func newHardware(exact []part, atLeast []count) (Hardware, error) { exact, atLeast = slices.Clone(exact), slices.Clone(atLeast) slices.SortFunc(exact, func(a, b part) int { return strings.Compare(a.Name, b.Name) }) @@ -77,6 +79,9 @@ func newHardware(exact []part, atLeast []count) (Hardware, error) { names = append(names, c.Name) } for _, n := range names { + if n == "" { + return Hardware{}, errors.New("the machine names a fact with no name") + } if seen[n] { return Hardware{}, fmt.Errorf("the machine names %q twice", n) } diff --git a/machine/record_test.go b/machine/record_test.go index bd3fb1e1..04aafb37 100644 --- a/machine/record_test.go +++ b/machine/record_test.go @@ -46,7 +46,7 @@ func spinsMachine() facts { } } -func (f facts) machine(t *testing.T) Hardware { +func (f facts) machine(t testing.TB) Hardware { t.Helper() var exact []part for n, v := range f.exact { @@ -67,7 +67,7 @@ var spinsCPU = CPU{Vendor: "GenuineIntel", Model: "host", Features: []string{"av Properties: map[string]string{"family": "6", "phys-bits": "46", "x-consistent-cache": "false"}} // target is a QEMU 11.2.0 machine of spin's shape, changed by edit. -func target(t *testing.T, edit func(*Target, facts)) Target { +func target(t testing.TB, edit func(*Target, facts)) Target { t.Helper() f := spinsMachine() tg := Target{VMM: "qemu 11.2.0", Formats: []string{FormatMappedRAM, FormatStream}, CPU: spinsCPU} @@ -283,7 +283,7 @@ func TestARecordHasOneForm(t *testing.T) { if empty, _ := json.Marshal(Hardware{}); string(empty) != `{"exact":[]}` { t.Errorf("an empty machine is %s, want one form", empty) } - for _, bad := range []string{`{"exact":[{"name":"a","value":"1"},{"name":"a","value":"2"}]}`, `{"exact":"x"}`} { + for _, bad := range []string{`{"exact":[{"name":"a","value":"1"},{"name":"a","value":"2"}]}`, `{"exact":"x"}`, `{"exact":[{"value":"1"}]}`} { if err := json.Unmarshal([]byte(bad), &read); err == nil || !strings.Contains(err.Error(), "machine record") { t.Errorf("read %s: %v, want it refused", bad, err) } diff --git a/machine/testdata/fuzz/FuzzCanResume/70b80e76ed1cfe20 b/machine/testdata/fuzz/FuzzCanResume/70b80e76ed1cfe20 new file mode 100644 index 00000000..09ea4c94 --- /dev/null +++ b/machine/testdata/fuzz/FuzzCanResume/70b80e76ed1cfe20 @@ -0,0 +1,3 @@ +go test fuzz v1 +[]byte("{\"format\":\"qemu-stream\",\"from\":{\"vmm\":\"qemu 11.2.0\",\"formats\":[\"qemu-mapped-ram\",\"qemu-stream\"],\"cpu\":{\"vendor\":\"GenuineIntel\",\"model\":\"host\",\"features\":[\"avx2\",\"sse4.1\",\"xsave\"]},\"machine\":{\"exact\":[{\"name\":\"accel\",\"value\":\"kvm\"},{\"name\":\"device 02.0\",\"value\":\"vhost-vsock-pci\"},{\"name\":\"device 02.0 disable-legacy\",\"value\":\"on\"},{\"name\":\"device 04.0\",\"value\":\"virtio-balloon-pci\"},{\"name\":\"device 04.0 deflate-on-oom\",\"value\":\"true\"},{\"name\":\"device 10.0\",\"value\":\"virtio-net-pci\"},{\"name\":\"device 10.0 host_mtu\",\"value\":\"1450\"},{\"name\":\"device 1a.0\",\"value\":\"virtio-scsi-pci\"},{\"name\":\"device 1f.0\",\"value\":\"ICH9-LPC\"},{\"namX\":\"device 1f.0 disable_s3\",\"value\":\"1\"},{\"name\":\"device i8257/1\",\"value\":\"i8257\"},{\"name\":\"machine memory.size\",\"value\":\"134217728\"},{\"name\":\"machine smp.cpus\",\"value\":\"1\"},{\"name\":\"machine smp.maxcpus\",\"value\":\"16\"},{\"name\":\"machine type\",\"value\":\"pc-q35-11.1\"},{\"name\":\"ram 0000:00:1e.0/mem.growth\",\"value\":\"8455716864\"},{\"name\":\"ram pc.bios\",\"value\":\"65536\"},{\"name\":\"ram pc.ram\",\"value\":\"134217728\"}],\"at_least\":[{\"name\":\"device 1a.0 max_target\",\"n\":15}]}}}") +[]byte("{\"format\":\"qemu-mapped-ram\",\"from\":{\"vmm\":\"qemu 11.2.0\",\"formats\":[\"qemu-mapped-ram\",\"qemu-stream\"],\"cpu\":{\"vendor\":\"GenuineIntel\",\"model\":\"host\",\"features\":[\"avx2\",\"sse4.1\",\"xsave\"],\"properties\":{\"family\":\"6\",\"phys-bits\":\"46\",\"maconsistent-cache\":\"false\"}},\"machine\":{\"exact\":[{\"name\":\"accel\",\"value\":\"kvm\"},{\"name\":\"device 02.0\",\"value\":\"vhost-vsock-pci\"},{\"name\":\"device 02.0 disable-legacy\",\"value\":\"on\"},{\"name\":\"device 04.0\",\"value\":\"virtio-balloon-pci\"},{\"name\":\"device 04.0 deflate-on-oom\",\"value\":\"true\"},{\"name\":\"device 10.0\",\"value\":\"virtio-net-pci\"},{\"name\":\"device 10.0 host_mtu\",\"value\":\"1450\"},{\"name\":\"device 1a.0\",\"value\":\"virtio-scsi-pci\"},{\"name\":\"device 1f.0\",\"value\":\"ICH9-LPC\"},{\"name\":\"device 1f.0 disable_s3\",\"value\":\"1\"},{\"name\":\"device i8257/1\",\"value\":\"i8257\"},{\"name\":\"machine memory.size\",\"value\":\"134217728\"},{\"name\":\"machine smp.cpus\",\"value\":\"1\"},{\"name\":\"machine smp.maxcpus\",\"value\":\"16\"},{\"name\":\"machine type\",\"value\":\"pc-q35-11.1\"},{\"name\":\"ram 0000:00:1e.0/mem.growth\",\"value\":\"8455716864\"},{\"name\":\"ram pc.bios\",\"value\":\"65536\"},{\"name\":\"ram pc.ram\",\"value\":\"134217728\"}],\"at_least\":[{\"name\":\"device 1a.0 max_target\",\"n\":15}]}},\"added\":{\"cpus\":[{\"id\":\"cpu-1\",\"driver\":\"host-x86_64-cpu\",\"props\":{\"socket-id\":1,\"core-id\":0,\"thread-id\":0}}],\"disks\":[{\"serial\":\"ext\",\"target\":3}]}}") diff --git a/qmp/fuzz_test.go b/qmp/fuzz_test.go new file mode 100644 index 00000000..5a488d40 --- /dev/null +++ b/qmp/fuzz_test.go @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: Apache-2.0 + +package qmp + +import ( + "bytes" + "context" + "io" + "sync" + "testing" + "time" + + "github.com/spin-stack/machine/internal/qmpdef" +) + +// A QEMU the guest has taken over writes whatever it likes to its monitor, and the client reads +// it on the host (#653). Whatever it writes, the client neither panics nor hangs: every call +// returns once the connection ends, and the connection ends with what QEMU wrote. + +// scripted is a QEMU that says its lines in turns: chunk 0 at once, and chunk i once the client +// has written its i-th line. Turns make each run of the fuzz target the same run: lines that +// all came at once would race the calls they answer. +type scripted struct { + mu sync.Mutex + turn *sync.Cond + chunks [][]byte + said int // chunks said + writes int + reading *bytes.Reader + closed bool +} + +func newScripted(input []byte) *scripted { + s := &scripted{chunks: bytes.Split(input, []byte("\n\n"))} + s.turn = sync.NewCond(&s.mu) + return s +} + +func (s *scripted) Read(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + for { + if s.closed { + return 0, io.ErrClosedPipe + } + if s.reading != nil && s.reading.Len() > 0 { + return s.reading.Read(p) + } + if s.said == len(s.chunks) { + return 0, io.EOF + } + if s.said <= s.writes { + s.reading = bytes.NewReader(append(s.chunks[s.said], '\n')) + s.said++ + continue + } + s.turn.Wait() + } +} + +func (s *scripted) WriteLine(_ context.Context, _ []byte, _ File) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return io.ErrClosedPipe + } + s.writes++ + s.turn.Broadcast() + return nil +} + +// rest says every chunk left, whatever the client writes. +func (s *scripted) rest() { + s.mu.Lock() + defer s.mu.Unlock() + s.writes = len(s.chunks) + s.turn.Broadcast() +} + +func (s *scripted) Close() error { + s.mu.Lock() + defer s.mu.Unlock() + s.closed = true + s.turn.Broadcast() + return nil +} + +var ( + queryImage = qmpdef.Define[None, []ImageInfo]("x-query-image") + anything = qmpdef.DefineEvent[map[string]any]("X_ANYTHING") +) + +func FuzzWhatQEMUSays(f *testing.F) { + greeting := `{"QMP": {"version": {"qemu": {"micro": 0, "minor": 2, "major": 11}, "package": ""}, "capabilities": []}}` + for _, seed := range []string{ + greeting + "\n\n" + `{"return": {}, "id": 1}` + "\n\n" + + `{"event": "X_ANYTHING", "data": {"a": [1, {"b": null}]}, "timestamp": {"seconds": 1, "microseconds": 2}}` + "\n" + + `{"return": [{"filename": "o.qcow2", "format-specific": {"type": "qcow2", "data": {"corrupt": true}}, "backing-image": {"filename": "base"}}], "id": 2}`, + greeting + "\n\n" + `{"error": {"class": "GenericError", "desc": "no"}, "id": 1}`, + greeting + "\n\n" + `{"return": {}, "id": 1}` + "\n\n" + `{"return": {}, "id": 7}` + "\n" + `{"event": "STOP"}`, + `{"return": {}}`, + } { + f.Add([]byte(seed)) + } + f.Fuzz(func(t *testing.T, input []byte) { + // A QEMU that never answers holds a call until its ctx ends, as it holds New's: that is + // the caller's bound, not a hang. A hang is a connection that outlives QEMU's end. + quick := func() context.Context { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + t.Cleanup(cancel) + return ctx + } + qemu := newScripted(input) + c, err := New(quick(), qemu, Observer{}) + if err != nil { + return + } + defer func() { _ = c.Close() }() + events := Expect(c, anything, nil) + defer events.Stop() + _, _ = Do(quick(), c, queryImage, None{}) + _, _ = Do(quick(), c, queryImage, None{}) + _, _ = Last(c, anything) + qemu.rest() + select { + case <-c.Done(): + case <-time.After(5 * time.Second): + t.Fatal("the connection outlived what QEMU said") + } + if c.Err() == nil { + t.Fatal("the connection ended and says no error") + } + }) +}