government / src / lisp2gov / cert_test.go

@ 0e917e8745ac2e1b54a9a68e4f106de8b2316ac6 | history


package lisp2gov

import (
	"bytes"
	"crypto/ed25519"
	"crypto/x509"
	"encoding/pem"
	"flag"
	"os"
	"testing"

	"government/ast"
)

var update = flag.Bool("update", false, "rewrite golden files in testdata")

// answer compiles the program 42, the smallest kind of GOVERNMENT program:
// one atom, so one cert below the anchor.
func answer() ([]byte, error) {
	return Compile("42", Options{Name: "answer"})
}

func parsePEM(t *testing.T, b []byte) []*x509.Certificate {
	t.Helper()
	var certs []*x509.Certificate
	for {
		var block *pem.Block
		block, b = pem.Decode(b)
		if block == nil {
			break
		}
		c, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			t.Fatal(err)
		}
		certs = append(certs, c)
	}
	return certs
}

func TestAnswerIsDeterministic(t *testing.T) {
	a, err := answer()
	if err != nil {
		t.Fatal(err)
	}
	b, err := answer()
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(a, b) {
		t.Fatal("two runs gave different bytes")
	}

	// The golden file pins the bytes across machines and Go releases too,
	// and is the file to inspect with openssl.
	const golden = "testdata/answer.gov"
	if *update {
		if err := os.WriteFile(golden, a, 0o644); err != nil {
			t.Fatal(err)
		}
	}
	want, err := os.ReadFile(golden)
	if err != nil {
		t.Fatalf("%v (run go test ./lisp2gov -update to create it)", err)
	}
	if !bytes.Equal(a, want) {
		t.Errorf("output differs from %s", golden)
	}
}

func TestAnswerSignatures(t *testing.T) {
	out, err := answer()
	if err != nil {
		t.Fatal(err)
	}
	certs := parsePEM(t, out)
	if len(certs) != 2 {
		t.Fatalf("%d certs, want 2", len(certs))
	}
	anchor, child := certs[0], certs[1]

	if err := anchor.CheckSignatureFrom(anchor); err != nil {
		t.Errorf("anchor is not self-signed: %v", err)
	}
	if err := child.CheckSignatureFrom(anchor); err != nil {
		t.Errorf("child.CheckSignatureFrom(anchor): %v", err)
	}
	if err := anchor.CheckSignatureFrom(child); err == nil {
		t.Error("the child, a non-CA, verified as the anchor's issuer")
	}
	if !bytes.Equal(child.AuthorityKeyId, anchor.SubjectKeyId) {
		t.Error("child's AKI does not name the anchor's key")
	}
	if !bytes.Equal(child.RawIssuer, anchor.RawSubject) {
		t.Error("child's issuer is not the anchor's subject")
	}
}

func TestAnswerProfile(t *testing.T) {
	out, err := answer()
	if err != nil {
		t.Fatal(err)
	}
	certs := parsePEM(t, out)
	anchor, child := certs[0], certs[1]
	checks := []struct {
		name string
		ok   bool
	}{
		{"anchor serial 1", anchor.SerialNumber.Int64() == 1},
		{"child serial 2", child.SerialNumber.Int64() == 2},
		{"anchor is a CA", anchor.IsCA && anchor.BasicConstraintsValid},
		{"child is not a CA", !child.IsCA && child.BasicConstraintsValid},
		{"anchor signs certs and CRLs", anchor.KeyUsage == x509.KeyUsageCertSign|x509.KeyUsageCRLSign},
		{"child signs data only", child.KeyUsage == x509.KeyUsageDigitalSignature},
		{"anchor names its own key", bytes.Equal(anchor.AuthorityKeyId, anchor.SubjectKeyId)},
		{"child has a key id", len(child.SubjectKeyId) == 20},
		{"v3", anchor.Version == 3 && child.Version == 3},
		{"Ed25519", child.SignatureAlgorithm == x509.PureEd25519},
		{"child subject", child.Subject.CommonName == "GOVERNMENT Depth 1"},
		{"program name", child.Subject.Organization[0] == "answer"},
		{"anchor has no policies", len(anchor.Policies) == 0},
		{"window", child.NotBefore.Equal(defaultNotBefore) && child.NotAfter.Equal(defaultNotAfter)},
	}
	for _, c := range checks {
		if !c.ok {
			t.Errorf("%s: no", c.name)
		}
	}
}

func TestKeysDifferByDepth(t *testing.T) {
	seen := map[string]int{}
	for i := 0; i < 5; i++ {
		k := string(keyForDepth(DefaultSeed, i).Public().(ed25519.PublicKey))
		if prev, ok := seen[k]; ok {
			t.Errorf("depths %d and %d share a key", prev, i)
		}
		seen[k] = i
	}
	other := keyForDepth([32]byte{1}, 1)
	if other.Equal(keyForDepth(DefaultSeed, 1)) {
		t.Error("two seeds gave the same depth-1 key")
	}
}

func TestAnswerPolicy(t *testing.T) {
	out, err := answer()
	if err != nil {
		t.Fatal(err)
	}
	certs := parsePEM(t, out)
	policies := certs[1].Policies
	if len(policies) != 1 {
		t.Fatalf("cert 1 has %d policies, want 1", len(policies))
	}
	ns, id, text, err := ast.DecodeOID(policies[0])
	if err != nil {
		t.Fatal(err)
	}
	if ns != ast.NSInt || id != 1 || text != "42" {
		t.Errorf("cert 1's policy decodes to %s #%d %q, want integer #1 \"42\"", ns, id, text)
	}
}