government

commit 0a6d0b45c9b0e3f50876896c1c597c24311ceb7b

tree

parent:
405825f89f1aafd129e6aa5b5bd6efeebe66616e

nmyk <nick@nmyk.io>

2026-11-14T15:53:57-05:00

add lisp2gov POC

diff --git a/lisp2gov/cert.go b/lisp2gov/cert.go
new file mode 100644
index 0000000000000000000000000000000000000000..82e7c610af77fd5766b62b1977716052bd52cdad
--- /dev/null
+++ b/lisp2gov/cert.go
@@ -0,0 +1,147 @@
+package lisp2gov
+
+import (
+	"bytes"
+	"crypto/ed25519"
+	"crypto/rand"
+	"crypto/sha256"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/pem"
+	"fmt"
+	"math/big"
+	"time"
+
+	"government/ast"
+	"government/sexpr"
+)
+
+// The default window in force. 9999-12-31 is RFC 5280's value for a
+// certificate with no well-defined expiration.
+var (
+	defaultEffective = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
+	defaultExpires   = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
+)
+
+// signer is a certificate together with the key that signs the next one.
+type signer struct {
+	cert *x509.Certificate
+	key  ed25519.PrivateKey
+}
+
+// newAnchor makes the self-signed trust anchor. It carries no policies:
+// the policy tree starts below it, at cert 1.
+func newAnchor(seed [32]byte, program string) (signer, error) {
+	key := keyForDepth(seed, 0)
+	pub := key.Public().(ed25519.PublicKey)
+	tmpl := &x509.Certificate{
+		SerialNumber:          big.NewInt(1),
+		Subject:               pkix.Name{CommonName: "GOVERNMENT Anchor", Organization: []string{program}},
+		NotBefore:             defaultEffective,
+		NotAfter:              defaultExpires,
+		BasicConstraintsValid: true,
+		IsCA:                  true,
+		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
+		SubjectKeyId:          keyID(pub),
+		AuthorityKeyId:        keyID(pub),
+	}
+	return create(tmpl, tmpl, pub, key, key)
+}
+
+// newCert makes the cert at depth i, issued by parent. Every cert but the
+// last is a CA, because each one signs the next; the last one signs
+// nothing.
+func newCert(seed [32]byte, program string, i int, last bool, policies []x509.OID, parent signer) (signer, error) {
+	key := keyForDepth(seed, i)
+	pub := key.Public().(ed25519.PublicKey)
+	tmpl := &x509.Certificate{
+		SerialNumber:          big.NewInt(int64(i + 1)),
+		Subject:               pkix.Name{CommonName: fmt.Sprintf("GOVERNMENT Depth %d", i), Organization: []string{program}},
+		NotBefore:             defaultEffective,
+		NotAfter:              defaultExpires,
+		BasicConstraintsValid: true,
+		IsCA:                  !last,
+		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
+		SubjectKeyId:          keyID(pub),
+		Policies:              policies,
+	}
+	if last {
+		tmpl.KeyUsage = x509.KeyUsageDigitalSignature
+	}
+	return create(tmpl, parent.cert, pub, parent.key, key)
+}
+
+func create(tmpl, parent *x509.Certificate, pub ed25519.PublicKey, signWith, own ed25519.PrivateKey) (signer, error) {
+	// Ed25519 signatures use no randomness, and the serial is set, so rand
+	// is never read and the output is deterministic.
+	der, err := x509.CreateCertificate(rand.Reader, tmpl, parent, pub, signWith)
+	if err != nil {
+		return signer{}, err
+	}
+	cert, err := x509.ParseCertificate(der)
+	if err != nil {
+		return signer{}, err
+	}
+	return signer{cert, own}, nil
+}
+
+// keyID is RFC 7093 method 1: the leftmost 160 bits of the SHA-256 of the
+// public key. Go would compute a key id for CA certs on its own, but not for
+// the last cert, and its choice of hash has changed between releases;
+// setting it here keeps every cert's bytes the same across Go versions.
+func keyID(pub ed25519.PublicKey) []byte {
+	sum := sha256.Sum256(pub)
+	return sum[:20]
+}
+
+// encodePEM writes the certs as PEM blocks after a header. Text outside
+// PEM blocks is ignored by readers, so the header can carry the source.
+func encodePEM(header string, certs []*x509.Certificate) []byte {
+	var b bytes.Buffer
+	b.WriteString(header)
+	for _, c := range certs {
+		pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: c.Raw})
+	}
+	return b.Bytes()
+}
+
+// firstProgram is the step-18 experiment: a program whose forms are all
+// atoms, so its tree has depth 1. That needs only the anchor and cert 1,
+// with each form as a policy, and no mappings, so Go can write every byte
+// itself. Compile replaces it once the policy extensions are hand-encoded.
+func firstProgram(seed [32]byte, name, src string) ([]byte, error) {
+	forms, err := sexpr.ReadAll(src)
+	if err != nil {
+		return nil, err
+	}
+	tree, err := ast.ToTree(forms)
+	if err != nil {
+		return nil, err
+	}
+	layers, err := ast.Layer(tree)
+	if err != nil {
+		return nil, err
+	}
+	if layers.Depth() != 1 {
+		return nil, fmt.Errorf("firstProgram handles depth 1 only; %q has depth %d", src, layers.Depth())
+	}
+	var policies []x509.OID
+	for _, n := range layers.Nodes[0] {
+		oid, err := n.OID()
+		if err != nil {
+			return nil, err
+		}
+		policies = append(policies, oid)
+	}
+
+	anchor, err := newAnchor(seed, name)
+	if err != nil {
+		return nil, err
+	}
+	cert1, err := newCert(seed, name, 1, true, policies, anchor)
+	if err != nil {
+		return nil, err
+	}
+	header := "; " + name + ".gov\n" + src + "\n\n"
+	return encodePEM(header, []*x509.Certificate{anchor.cert, cert1.cert}), nil
+}
diff --git a/lisp2gov/cert_test.go b/lisp2gov/cert_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bbe0559b88cf38d6e858c99f069de51f73fc50e3
--- /dev/null
+++ b/lisp2gov/cert_test.go
@@ -0,0 +1,170 @@
+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 firstProgram(DefaultSeed, "answer", "42")
+}
+
+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(defaultEffective) && child.NotAfter.Equal(defaultExpires)},
+	}
+	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)
+	}
+}
+
+func TestFirstProgramRejectsDeeperPrograms(t *testing.T) {
+	if _, err := firstProgram(DefaultSeed, "deep", "(+ 1 2)"); err == nil {
+		t.Error("a depth-2 program compiled without policy mappings")
+	}
+}
diff --git a/lisp2gov/doc.go b/lisp2gov/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..bc2785eda9de2484619ea23745efd6c57aa9b792
--- /dev/null
+++ b/lisp2gov/doc.go
@@ -0,0 +1,3 @@
+// Package lisp2gov compiles Lisp source into a .gov file: a trust anchor
+// followed by one certificate per depth of the program tree.
+package lisp2gov
diff --git a/lisp2gov/keys.go b/lisp2gov/keys.go
new file mode 100644
index 0000000000000000000000000000000000000000..ea6a10c6b58af51f6d6bf444c95e3c6e86ee2faf
--- /dev/null
+++ b/lisp2gov/keys.go
@@ -0,0 +1,26 @@
+package lisp2gov
+
+import (
+	"crypto/ed25519"
+	"crypto/sha256"
+	"strconv"
+)
+
+// DefaultSeed signs programs compiled without an author key. It is public
+// on purpose: anyone can rebuild, amend or repeal such a program, and
+// `government verify` says so.
+var DefaultSeed = sha256.Sum256([]byte("GOVERNMENT"))
+
+// keyForDepth returns the signing key of the cert at depth i (0 is the
+// anchor). Deriving every key from one seed keeps output deterministic and
+// means the seed's holder alone can rebuild the chain or sign repeals.
+func keyForDepth(seed [32]byte, i int) ed25519.PrivateKey {
+	if i == 0 {
+		return ed25519.NewKeyFromSeed(seed[:])
+	}
+	h := sha256.New()
+	h.Write(seed[:])
+	h.Write([]byte("GOVERNMENT"))
+	h.Write([]byte(strconv.Itoa(i)))
+	return ed25519.NewKeyFromSeed(h.Sum(nil))
+}
diff --git a/lisp2gov/testdata/answer.gov b/lisp2gov/testdata/answer.gov
new file mode 100644
index 0000000000000000000000000000000000000000..64f893d1027ef6982fbbc935a2347c889d527776
--- /dev/null
+++ b/lisp2gov/testdata/answer.gov
@@ -0,0 +1,24 @@
+; answer.gov
+42
+
+-----BEGIN CERTIFICATE-----
+MIIBbjCCASCgAwIBAgIBATAFBgMrZXAwLTEPMA0GA1UEChMGYW5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