government / src / lisp2gov / golden_test.go

@ 27e33aecf4976d7646339e35c5fff6755a29497c | history


package lisp2gov

import (
	"bytes"
	"encoding/pem"
	"fmt"
	"os"
	"testing"
	"time"

	"government/eval"
	"government/internal/lisptest"
	"government/program"
)

// The golden program is built with every option fixed, so its bytes
// depend on nothing but the compiler.
var (
	goldenSeed = [32]byte{'g', 'o', 'l', 'd', 'e', 'n'}
	goldenOpts = Options{
		Name:      "golden",
		Seed:      &goldenSeed,
		Author:    "Ada Lovelace <ada@example.org>",
		NotBefore: time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC),
		NotAfter:  time.Date(2037, 1, 1, 0, 0, 0, 0, time.UTC),
	}
	goldenRepeal = RepealOptions{
		Seed:       &goldenSeed,
		Reason:     4, // superseded
		At:         time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC),
		LastUpdate: time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC),
		NextUpdate: time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC),
	}
)

// TestGolden compiles testdata/golden.gov.lisp, which uses every part of
// the encoding, and repeals it, and compares both results byte for byte
// with the checked-in files. Anyone can rebuild them and get the same
// bytes, so any difference is a change to the format: either a bug, or a
// deliberate change to accept with go test ./lisp2gov -update.
func TestGolden(t *testing.T) {
	src, err := os.ReadFile("testdata/golden.gov.lisp")
	if err != nil {
		t.Fatal(err)
	}
	gov, err := Compile(string(src), goldenOpts)
	if err != nil {
		t.Fatal(err)
	}
	certs := parsePEM(t, gov)
	crl, err := Repeal(certs, goldenRepeal)
	if err != nil {
		t.Fatal(err)
	}
	compareGolden(t, "testdata/golden.gov", gov)
	compareGolden(t, "testdata/golden.crl", crl)

	// The golden program must also be a working one, so the file stays
	// worth inspecting.
	if len(certs) < 4 {
		t.Errorf("golden program has %d certs; it should be deep enough to have mappings", len(certs))
	}
	p, err := program.Load(gov, program.Options{At: time.Date(2028, 1, 1, 0, 0, 0, 0, time.UTC)})
	if err != nil {
		t.Fatal(err)
	}
	f, err := lisptest.Parse("testdata/golden.gov.lisp", string(src))
	if err != nil {
		t.Fatal(err)
	}
	compiled, err := f.WithForms(p.Forms)
	if err != nil {
		t.Fatal(err)
	}
	lisptest.Run(t, compiled, eval.NewTopLevel())
}

func compareGolden(t *testing.T, path string, got []byte) {
	t.Helper()
	if *update {
		if err := os.WriteFile(path, got, 0o644); err != nil {
			t.Fatal(err)
		}
	}
	want, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("%v (run go test ./lisp2gov -update to create it)", err)
	}
	if diff := firstDifference(want, got); diff != "" {
		t.Errorf("%s: %s (if the change is intended, run go test ./lisp2gov -update)", path, diff)
	}
}

// firstDifference describes where two PEM files first differ: which block,
// and which byte of its DER, so a failure points at a field rather than at
// a line of base64.
func firstDifference(want, got []byte) string {
	if bytes.Equal(want, got) {
		return ""
	}
	for block := 0; ; block++ {
		w, wrest := pem.Decode(want)
		g, grest := pem.Decode(got)
		switch {
		case w == nil && g == nil:
			return "the PEM text differs outside its blocks"
		case w == nil:
			return fmt.Sprintf("block %d is new", block)
		case g == nil:
			return fmt.Sprintf("block %d is missing", block)
		}
		if w.Type != g.Type {
			return fmt.Sprintf("block %d is a %s, want a %s", block, g.Type, w.Type)
		}
		if !bytes.Equal(w.Bytes, g.Bytes) {
			i := 0
			for i < len(w.Bytes) && i < len(g.Bytes) && w.Bytes[i] == g.Bytes[i] {
				i++
			}
			return fmt.Sprintf("block %d (%s) differs from DER byte %d of %d (now %d bytes long)",
				block, w.Type, i, len(w.Bytes), len(g.Bytes))
		}
		want, got = wrest, grest
	}
}

// TestFirstDifference checks that a change to any one byte is caught and
// placed: the golden comparison is only as good as this.
func TestFirstDifference(t *testing.T) {
	gov, err := Compile("(+ 1 (* 2 3))", Options{})
	if err != nil {
		t.Fatal(err)
	}
	if d := firstDifference(gov, gov); d != "" {
		t.Errorf("identical files: %s", d)
	}
	blocks := pemBlocks(gov)
	for b, der := range blocks {
		for _, i := range []int{0, len(der) / 2, len(der) - 1} {
			changed := make([][]byte, len(blocks))
			copy(changed, blocks)
			changed[b] = bytes.Clone(der)
			changed[b][i] ^= 1
			want := fmt.Sprintf("block %d (CERTIFICATE) differs from DER byte %d of", b, i)
			if d := firstDifference(gov, encodeBlocks(changed)); !bytes.HasPrefix([]byte(d), []byte(want)) {
				t.Errorf("flipping byte %d of block %d: %q", i, b, d)
			}
		}
	}
	if d := firstDifference(gov, encodeBlocks(blocks[:len(blocks)-1])); d != fmt.Sprintf("block %d is missing", len(blocks)-1) {
		t.Errorf("dropped block: %q", d)
	}
}

func pemBlocks(data []byte) [][]byte {
	var out [][]byte
	for {
		var b *pem.Block
		b, data = pem.Decode(data)
		if b == nil {
			return out
		}
		out = append(out, b.Bytes)
	}
}

func encodeBlocks(blocks [][]byte) []byte {
	var out []byte
	for _, b := range blocks {
		out = append(out, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b})...)
	}
	return out
}