government / cmd / government / anchor_test.go

@ 20dc26e627d8341795ca628664e44a83b66d316a | history


package main

import (
	"io"
	"os"
	"path/filepath"
	"testing"

	"github.com/spf13/pflag"

	"government/lisp2gov"
	"government/ratify"
)

func TestAnchorFlag(t *testing.T) {
	dir := t.TempDir()
	prog := filepath.Join(dir, "p.gov")
	out, err := lisp2gov.Compile("(+ 1 2)", lisp2gov.Options{})
	if err != nil {
		t.Fatal(err)
	}
	os.WriteFile(prog, out, 0o644)
	junk := filepath.Join(dir, "junk.txt")
	os.WriteFile(junk, []byte("not a key"), 0o644)

	parse := func(args ...string) (*anchorFlag, error) {
		fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
		fs.SetOutput(io.Discard)
		a := addAnchorFlag(fs)
		return a, fs.Parse(args)
	}

	a, err := parse()
	if err != nil || a.Pin() != nil {
		t.Errorf("no -anchor: pin %v, err %v; want none", a.Pin(), err)
	}

	a, err = parse("--anchor", prog)
	if err != nil {
		t.Fatal(err)
	}
	certs, _ := ratify.Load(out)
	if err := ratify.CheckPin(certs[0], a.Pin()); err != nil {
		t.Errorf("pin from the program itself: %v", err)
	}

	for _, bad := range []string{junk, filepath.Join(dir, "missing.pem")} {
		if _, err := parse("--anchor", bad); err == nil {
			t.Errorf("-anchor %s accepted", bad)
		}
	}
}