government / cmd / government / verify_test.go

@ 20dc26e627d8341795ca628664e44a83b66d316a | history


package main

import (
	"encoding/pem"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"government/lisp2gov"
)

func TestVerifyPrintsCertificate(t *testing.T) {
	gov := compileTo(t, t.TempDir(), "worked", "(+ 1 (* 2 3))")
	code, stdout, stderr := runCmd("verify", gov)
	if code != exitOK {
		t.Fatalf("exit %d: %s", code, stderr)
	}
	for _, want := range []string{
		"CERTIFICATE OF RATIFICATION",
		"Program      worked",
		"Ratified by  nobody in particular (default key)",
		"Key          SHA-256 ",
		"In force     2000-01-01T00:00:00Z to 9999-12-31T23:59:59Z",
		"Depth        3 ",
		"Nodes        7\n",
	} {
		if !strings.Contains(stdout, want) {
			t.Errorf("missing %q in\n%s", want, stdout)
		}
	}
}

func TestVerifyNamesARealAuthor(t *testing.T) {
	seed := [32]byte{7}
	data, err := lisp2gov.Compile("1", lisp2gov.Options{Name: "mine", Seed: &seed})
	if err != nil {
		t.Fatal(err)
	}
	gov := filepath.Join(t.TempDir(), "mine.gov")
	os.WriteFile(gov, data, 0o644)
	_, stdout, _ := runCmd("verify", gov)
	if !strings.Contains(stdout, "Ratified by  GOVERNMENT Anchor\n") {
		t.Errorf("a program from its own seed is not reported by its anchor:\n%s", stdout)
	}
}

// pemBlocks splits a .gov file into its DER blocks.
func pemBlocks(t *testing.T, path string) [][]byte {
	t.Helper()
	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}
	var out [][]byte
	for {
		var b *pem.Block
		b, data = pem.Decode(data)
		if b == nil {
			return out
		}
		out = append(out, b.Bytes)
	}
}

func writeBlocks(t *testing.T, dir, name string, blocks [][]byte, typ ...string) string {
	t.Helper()
	var out []byte
	for i, der := range blocks {
		ty := "CERTIFICATE"
		if i < len(typ) && typ[i] != "" {
			ty = typ[i]
		}
		out = append(out, pem.EncodeToMemory(&pem.Block{Type: ty, Bytes: der})...)
	}
	path := filepath.Join(dir, name+".gov")
	os.WriteFile(path, out, 0o644)
	return path
}

// TestVerifyRefusesPhase4Mutations runs the Phase 4 failure cases through
// the command: each one exits 2 and names its error. Mutations that need a
// re-signed cert (clearing IsCA, adding a critical extension) are in
// ratify's own tests, which can sign.
func TestVerifyRefusesPhase4Mutations(t *testing.T) {
	dir := t.TempDir()
	gov := compileTo(t, dir, "p", "(+ 1 (* 2 3))")
	blocks := pemBlocks(t, gov)

	flipped := append([][]byte(nil), blocks...)
	der := append([]byte(nil), blocks[2]...)
	der[len(der)-1] ^= 0xff // the last byte of the signature
	flipped[2] = der

	seed := [32]byte{3}
	foreignData, _ := lisp2gov.Compile("(+ 1 (* 2 3))", lisp2gov.Options{Name: "p", Seed: &seed})
	foreign := filepath.Join(dir, "foreign.gov")
	os.WriteFile(foreign, foreignData, 0o644)

	tests := []struct {
		name string
		args []string
		want string
	}{
		{"flipped signature byte", []string{"verify", writeBlocks(t, dir, "flipped", flipped)}, "E-TAMPERED: clause at depth 2"},
		{"dropped depth", []string{"verify", writeBlocks(t, dir, "dropped", [][]byte{blocks[0], blocks[1], blocks[3]})}, "E-CHAIN"},
		{"duplicated cert", []string{"verify", writeBlocks(t, dir, "dup", append(append([][]byte(nil), blocks...), blocks[1]))}, "E-CHAIN"},
		{"private key block", []string{"verify", writeBlocks(t, dir, "key", append(append([][]byte(nil), blocks...), []byte{1}), "", "", "", "", "PRIVATE KEY")}, "E-MALFORMED"},
		{"expired", []string{"verify", gov, "--at", "9999-12-31T23:59:59.5Z"}, "E-LAPSED"},
		{"not yet in force", []string{"verify", gov, "--at", "1999-12-31T23:59:59Z"}, "E-NOT-IN-FORCE"},
		{"foreign key", []string{"verify", foreign, "--anchor", gov}, "E-FOREIGN"},
	}
	for _, tt := range tests {
		code, stdout, stderr := runCmd(tt.args...)
		if code != exitInvalid || !strings.Contains(stderr, tt.want) || stdout != "" {
			t.Errorf("%s: exit %d, stderr %q, stdout %q; want exit %d and %q", tt.name, code, stderr, stdout, exitInvalid, tt.want)
		}
	}

	// Order is not a mutation: a shuffled file is the same program.
	shuffled := writeBlocks(t, dir, "shuffled", [][]byte{blocks[3], blocks[1], blocks[0], blocks[2]})
	if code, _, stderr := runCmd("verify", shuffled); code != exitOK {
		t.Errorf("shuffled file: exit %d, %s", code, stderr)
	}
}