government / src / lisp2gov / author_test.go

@ main | history


package lisp2gov

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"reflect"
	"testing"
	"time"
)

// keyPEM writes an Ed25519 key the way openssl genpkey does.
func keyPEM(t *testing.T, seed byte) []byte {
	t.Helper()
	key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{seed}, 32))
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		t.Fatal(err)
	}
	return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})
}

func compileAs(t *testing.T, src string, keySeed byte, author string) []*x509.Certificate {
	t.Helper()
	seed, err := LoadKey(keyPEM(t, keySeed))
	if err != nil {
		t.Fatal(err)
	}
	out, err := Compile(src, Options{Name: "law", Seed: seed, Author: author})
	if err != nil {
		t.Fatal(err)
	}
	return parsePEM(t, out)
}

// TestTwoAuthors is the plan's check: two authors' builds of one source
// differ only in keys and names.
func TestTwoAuthors(t *testing.T) {
	src := "; the total\n(+ 1 (* 2 3))"
	ada := compileAs(t, src, 1, "Ada Lovelace <ada@example.com>")
	bob := compileAs(t, src, 2, "Bob")
	if len(ada) != len(bob) {
		t.Fatalf("%d certs and %d certs", len(ada), len(bob))
	}
	for i := range ada {
		a, b := ada[i], bob[i]
		same := []struct {
			what string
			x, y any
		}{
			{"policies", a.Policies, b.Policies},
			{"mappings", a.PolicyMappings, b.PolicyMappings},
			{"serial", a.SerialNumber, b.SerialNumber},
			{"window", [2]time.Time{a.NotBefore, a.NotAfter}, [2]time.Time{b.NotBefore, b.NotAfter}},
			{"key usage", a.KeyUsage, b.KeyUsage},
			{"CA flag", a.IsCA, b.IsCA},
			{"organization", a.Subject.Organization, b.Subject.Organization},
		}
		for _, s := range same {
			if !reflect.DeepEqual(s.x, s.y) {
				t.Errorf("cert %d: %s differs", i, s.what)
			}
		}
		if bytes.Equal(a.RawSubjectPublicKeyInfo, b.RawSubjectPublicKeyInfo) {
			t.Errorf("cert %d: both authors' builds have the same key", i)
		}
	}
	if ada[0].Subject.CommonName != "Ada Lovelace" || len(ada[0].EmailAddresses) != 1 || ada[0].EmailAddresses[0] != "ada@example.com" {
		t.Errorf("Ada's anchor: CN %q, emails %v", ada[0].Subject.CommonName, ada[0].EmailAddresses)
	}
	if bob[0].Subject.CommonName != "Bob" || len(bob[0].EmailAddresses) != 0 {
		t.Errorf("Bob's anchor: CN %q, emails %v", bob[0].Subject.CommonName, bob[0].EmailAddresses)
	}
}

func TestAnchorIsSignedWithTheAuthorKey(t *testing.T) {
	certs := compileAs(t, "1", 1, "Ada")
	want := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, 32)).Public()
	if !want.(ed25519.PublicKey).Equal(certs[0].PublicKey) {
		t.Error("the anchor's key is not the author's key")
	}
}

func TestKeyDerivation(t *testing.T) {
	// The design's formula: seed for depth i = SHA-256(seed || "GOVERNMENT" || i).
	seed := [32]byte{9}
	h := sha256.New()
	h.Write(seed[:])
	h.Write([]byte("GOVERNMENT3"))
	want := ed25519.NewKeyFromSeed(h.Sum(nil))
	if !keyForDepth(seed, 3).Equal(want) {
		t.Error("depth 3's key is not SHA-256(seed || \"GOVERNMENT\" || \"3\")")
	}
}

func TestParseAuthor(t *testing.T) {
	tests := []struct{ in, name, email string }{
		{"Ada Lovelace <ada@example.com>", "Ada Lovelace", "ada@example.com"},
		{"Ada Lovelace", "Ada Lovelace", ""},
		{"ada@example.com", "ada@example.com", "ada@example.com"},
		{"  ", "", ""},
	}
	for _, tt := range tests {
		name, email, err := parseAuthor(tt.in)
		if err != nil || name != tt.name || email != tt.email {
			t.Errorf("parseAuthor(%q) = %q, %q, %v", tt.in, name, email, err)
		}
	}
	if _, _, err := parseAuthor("Ada <not an email"); err == nil {
		t.Error("a broken address was accepted")
	}
}

func TestLoadKeyRejects(t *testing.T) {
	ec, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	der, _ := x509.MarshalPKCS8PrivateKey(ec)
	for name, data := range map[string][]byte{
		"not PEM":        []byte("hello"),
		"public key":     pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: []byte{1}}),
		"bad PKCS#8":     pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte{1, 2, 3}}),
		"an ECDSA key":   pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}),
		"an OpenSSH key": pem.EncodeToMemory(&pem.Block{Type: "OPENSSH PRIVATE KEY", Bytes: []byte("openssh-key-v1\x00")}),
	} {
		if _, err := LoadKey(data); err == nil {
			t.Errorf("%s: accepted", name)
		}
	}
}

func TestDates(t *testing.T) {
	from := time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)
	to := time.Date(2027, 12, 31, 0, 0, 0, 0, time.UTC)
	out, err := Compile("(+ 1 2)", Options{NotBefore: from, NotAfter: to})
	if err != nil {
		t.Fatal(err)
	}
	for i, c := range parsePEM(t, out) {
		if !c.NotBefore.Equal(from) || !c.NotAfter.Equal(to) {
			t.Errorf("cert %d: %s to %s", i, c.NotBefore, c.NotAfter)
		}
	}
	if _, err := Compile("1", Options{NotBefore: to, NotAfter: from}); err == nil {
		t.Error("a program that expires before it takes effect was compiled")
	}
}