government

commit 7eeb8a0214368f4491f26f4cf37bd7bf6dc67cd3

tree

parent:
5c83a9c6b185121b6a79d1e44755763853b4b6d5

nmyk <nick@nmyk.io>

2026-11-14T19:07:50-05:00

add repeal writing

diff --git a/cmd/government/main.go b/cmd/government/main.go
index 476ed21345b83a5d9b17becb00f991094f74efc0..b90e93af750920a1b7431ba5d34b185cb0d1c3fd 100644
--- a/cmd/government/main.go
+++ b/cmd/government/main.go
@@ -1,7 +1,5 @@
-// Command government runs GOVERNMENT programs.
-//
-// repeal arrives in a later step of PLAN.md. The other subcommands arrive in later steps
-// of PLAN.md.
+// Command government compiles, checks, inspects, runs and repeals
+// GOVERNMENT programs.
 package main
 
 import (
@@ -26,8 +24,6 @@   run        ratify, decode and evaluate a .gov program
   tree       print the policy tree
   decompile  print equivalent Lisp source
   verify     ratify and decode only, and print a certificate of ratification
-
-not yet implemented:
   repeal     write a CRL repealing one depth of a program
 `
 
@@ -51,6 +47,8 @@ 	case "decompile":
 		return decompile(args[1:], stdout, stderr)
 	case "verify":
 		return verify(args[1:], stdout, stderr)
+	case "repeal":
+		return repeal(args[1:], stdout, stderr)
 	case "help", "-h", "-help", "--help":
 		fmt.Fprint(stdout, usage)
 		return exitOK
diff --git a/cmd/government/repeal.go b/cmd/government/repeal.go
new file mode 100644
index 0000000000000000000000000000000000000000..154a2d92d9aac363d98b3c2d9655c5460f86b0a9
--- /dev/null
+++ b/cmd/government/repeal.go
@@ -0,0 +1,93 @@
+package main
+
+import (
+	"flag"
+	"fmt"
+	"io"
+	"os"
+	"strings"
+	"time"
+
+	"government/lisp2gov"
+	"government/ratify"
+)
+
+// repeal writes a CRL that strikes down one depth of a program, and with
+// it the whole program. It needs the key the program was compiled with.
+func repeal(args []string, stdout, stderr io.Writer) int {
+	fs := flag.NewFlagSet("repeal", flag.ContinueOnError)
+	fs.SetOutput(stderr)
+	depth := fs.Int("depth", 0, "repeal the cert at depth `i` (1 to the program's depth)")
+	out := fs.String("o", "", "write the CRL to `file` instead of standard output")
+	keyFile := fs.String("key", "", "the Ed25519 PKCS#8 private key `file` the program was compiled with")
+	seedHex := fs.String("seed", "", "the `hex` seed the program was compiled with, instead of a key file")
+	reason := fs.String("reason", "unspecified", "the CRLReason: `name` is one of "+strings.Join(lisp2gov.ReasonNames(), ", "))
+	var at, issued, nextUpdate dateFlag
+	fs.Var(&at, "at", "the repeal takes effect at this `time` (default now); a future time schedules it")
+	fs.Var(&issued, "issued", "the CRL's issue `time` (thisUpdate; default now)")
+	fs.Var(&nextUpdate, "next-update", "the CRL goes stale at this `time` (default 9999-12-31T23:59:59Z, never)")
+	fs.Usage = func() {
+		fmt.Fprintln(stderr, "usage: government repeal prog.gov -depth i [-o repeal.crl] [-key file | -seed hex]\n"+
+			"         [-reason name] [-at time] [-issued time] [-next-update time]")
+		fs.PrintDefaults()
+	}
+	path, data, ok := oneFile(fs, args, stderr)
+	if !ok {
+		return exitInvalid
+	}
+	code, known := lisp2gov.Reasons[*reason]
+	if !known {
+		fmt.Fprintf(stderr, "unknown reason %q; want one of %s\n", *reason, strings.Join(lisp2gov.ReasonNames(), ", "))
+		return exitInvalid
+	}
+	seed, err := signingSeed(*keyFile, *seedHex)
+	if err != nil {
+		fmt.Fprintln(stderr, err)
+		return exitInvalid
+	}
+
+	// A program is repealed whatever its dates, so only its chain is
+	// checked here, not its window in force.
+	certs, err := ratify.Load(data)
+	if err == nil {
+		certs, err = ratify.Order(certs)
+	}
+	if err == nil {
+		err = ratify.CheckChain(certs)
+	}
+	if err != nil {
+		fmt.Fprintf(stderr, "%s: %v\n", path, err)
+		return exitInvalid
+	}
+
+	now := time.Now().UTC().Truncate(time.Second)
+	opts := lisp2gov.RepealOptions{
+		Seed:       seed,
+		Reason:     code,
+		At:         orDefault(at.t, now),
+		Issued:     orDefault(issued.t, now),
+		NextUpdate: orDefault(nextUpdate.t, time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)),
+	}
+	crl, err := lisp2gov.Repeal(certs, *depth, opts)
+	if err != nil {
+		fmt.Fprintf(stderr, "%s: %v\n", path, err)
+		return exitInvalid
+	}
+	if *out == "" {
+		_, err = stdout.Write(crl)
+	} else {
+		err = os.WriteFile(*out, crl, 0o644)
+	}
+	if err != nil {
+		fmt.Fprintln(stderr, err)
+		return exitInvalid
+	}
+	return exitOK
+}
+
+func orDefault(t, def time.Time) time.Time {
+	if t.IsZero() {
+		return def
+	}
+	return t
+}
diff --git a/cmd/government/repeal_test.go b/cmd/government/repeal_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2e1c5afe3e0c2ff53a220bfd13fcad9ce25489e1
--- /dev/null
+++ b/cmd/government/repeal_test.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+	"crypto/x509"
+	"encoding/pem"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+func TestRepealCommand(t *testing.T) {
+	dir := t.TempDir()
+	key := writeKey(t, dir, "ada", 1)
+	src := writeSource(t, "law", "(+ 1 (* 2 3))")
+	gov := filepath.Join(dir, "law.gov")
+	if code, _, stderr := runCmd("compile", src, "-o", gov, "-key", key); code != exitOK {
+		t.Fatal(stderr)
+	}
+	crlPath := filepath.Join(dir, "repeal.crl")
+	code, _, stderr := runCmd("repeal", gov, "-depth", "2", "-key", key, "-reason", "superseded",
+		"-at", "2027-03-01", "-issued", "2027-02-01", "-o", crlPath)
+	if code != exitOK {
+		t.Fatalf("exit %d: %s", code, stderr)
+	}
+	data, _ := os.ReadFile(crlPath)
+	block, _ := pem.Decode(data)
+	crl, err := x509.ParseRevocationList(block.Bytes)
+	if err != nil {
+		t.Fatal(err)
+	}
+	certs := pemCerts(t, gov)
+	if err := crl.CheckSignatureFrom(certs[1]); err != nil {
+		t.Errorf("CRL does not verify against depth 1, the repealed cert's issuer: %v", err)
+	}
+	e := crl.RevokedCertificateEntries[0]
+	if e.SerialNumber.Int64() != 3 || e.ReasonCode != 4 || e.RevocationTime.Format("2006-01-02") != "2027-03-01" {
+		t.Errorf("entry: serial %v, reason %d, at %v", e.SerialNumber, e.ReasonCode, e.RevocationTime)
+	}
+}
+
+func TestRepealRefusals(t *testing.T) {
+	dir := t.TempDir()
+	key := writeKey(t, dir, "ada", 1)
+	other := writeKey(t, dir, "bob", 2)
+	src := writeSource(t, "law", "(+ 1 2)")
+	gov := filepath.Join(dir, "law.gov")
+	runCmd("compile", src, "-o", gov, "-key", key)
+	tests := []struct {
+		args []string
+		want string
+	}{
+		{[]string{"repeal", gov, "-depth", "1", "-key", other}, "did not compile"},
+		{[]string{"repeal", gov, "-depth", "1"}, "did not compile"},
+		{[]string{"repeal", gov, "-depth", "3", "-key", key}, "depths 1 to 2"},
+		{[]string{"repeal", gov, "-key", key}, "depths 1 to 2"},
+		{[]string{"repeal", gov, "-depth", "1", "-key", key, "-reason", "boredom"}, "unknown reason"},
+		{[]string{"repeal", gov, "-depth", "1", "-key", key, "-issued", "2027-01-01", "-next-update", "2026-01-01"}, "go stale"},
+		{[]string{"repeal"}, "usage"},
+	}
+	for _, tt := range tests {
+		code, _, stderr := runCmd(tt.args...)
+		if code != exitInvalid || !strings.Contains(stderr, tt.want) {
+			t.Errorf("%v: exit %d, %q; want %q", tt.args[1:], code, stderr, tt.want)
+		}
+	}
+}
+
+func pemCerts(t *testing.T, path string) []*x509.Certificate {
+	t.Helper()
+	var certs []*x509.Certificate
+	for _, der := range pemBlocks(t, path) {
+		c, err := x509.ParseCertificate(der)
+		if err != nil {
+			t.Fatal(err)
+		}
+		certs = append(certs, c)
+	}
+	return certs
+}
diff --git a/lisp2gov/author_test.go b/lisp2gov/author_test.go
index 4b4866db8805b43a56e01dee25e6d07a73682e03..67987256b1c27b8f70be5e085a632155476dfa01 100644
--- a/lisp2gov/author_test.go
+++ b/lisp2gov/author_test.go
@@ -120,10 +120,11 @@ 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}),
+		"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)
diff --git a/lisp2gov/repeal.go b/lisp2gov/repeal.go
new file mode 100644
index 0000000000000000000000000000000000000000..6d340b04b09f069b5bc179ee4c760949c19ba3a5
--- /dev/null
+++ b/lisp2gov/repeal.go
@@ -0,0 +1,104 @@
+package lisp2gov
+
+import (
+	"bytes"
+	"crypto/rand"
+	"crypto/x509"
+	"encoding/pem"
+	"fmt"
+	"math/big"
+	"slices"
+	"time"
+)
+
+// Reasons are RFC 5280's CRLReason codes (section 5.3.1), by name. Code 7
+// is unused in the RFC.
+var Reasons = map[string]int{
+	"unspecified":          0,
+	"keyCompromise":        1,
+	"cACompromise":         2,
+	"affiliationChanged":   3,
+	"superseded":           4,
+	"cessationOfOperation": 5,
+	"certificateHold":      6,
+	"removeFromCRL":        8,
+	"privilegeWithdrawn":   9,
+	"aACompromise":         10,
+}
+
+// ReasonNames lists the reason names in code order, for messages.
+func ReasonNames() []string {
+	names := make([]string, 0, len(Reasons))
+	for n := range Reasons {
+		names = append(names, n)
+	}
+	slices.SortFunc(names, func(a, b string) int { return Reasons[a] - Reasons[b] })
+	return names
+}
+
+type RepealOptions struct {
+	// Seed is the key the program was compiled with; nil means
+	// DefaultSeed. Repealing needs it because the cert being repealed is
+	// revoked by its issuer, the cert one depth up, whose key is derived
+	// from this seed.
+	Seed *[32]byte
+	// Reason is a CRLReason code.
+	Reason int
+	// At is when the repeal takes effect: the revocation time. A time in
+	// the future schedules the repeal.
+	At time.Time
+	// Issued is when the CRL is made (thisUpdate), and NextUpdate is when
+	// it goes stale. A CRL is only trusted until its nextUpdate, so a
+	// permanent repeal should have a far-off one.
+	Issued, NextUpdate time.Time
+}
+
+// Repeal makes a CRL that revokes the cert at depth of a program, given
+// its certs in depth order. Revoking any one depth breaks the chain, so it
+// repeals the whole program.
+//
+// By RFC 5280 a cert is revoked by its own issuer: the CRL is signed by
+// the cert at depth-1 (the anchor, for depth 1) and names the revoked cert
+// by its serial number, which is unique only among that issuer's certs.
+func Repeal(certs []*x509.Certificate, depth int, opts RepealOptions) ([]byte, error) {
+	n := len(certs) - 1
+	if depth < 1 || depth > n {
+		return nil, fmt.Errorf("depth %d: the program has depths 1 to %d", depth, n)
+	}
+	seed := DefaultSeed
+	if opts.Seed != nil {
+		seed = *opts.Seed
+	}
+	issuer, revoked := certs[depth-1], certs[depth]
+	key := keyForDepth(seed, depth-1)
+	pub, err := x509.MarshalPKIXPublicKey(key.Public())
+	if err != nil {
+		return nil, err
+	}
+	if !bytes.Equal(pub, issuer.RawSubjectPublicKeyInfo) {
+		return nil, fmt.Errorf("this key did not compile the program: depth %d's issuer has a different key", depth)
+	}
+	if !opts.NextUpdate.After(opts.Issued) {
+		return nil, fmt.Errorf("the CRL would go stale (%s) before it is issued (%s)",
+			opts.NextUpdate.UTC().Format(time.RFC3339), opts.Issued.UTC().Format(time.RFC3339))
+	}
+
+	tmpl := &x509.RevocationList{
+		// A CRL number should grow with each CRL an issuer publishes; the
+		// issue time in seconds does, and keeps the output deterministic.
+		Number:     big.NewInt(opts.Issued.Unix()),
+		ThisUpdate: opts.Issued.UTC(),
+		NextUpdate: opts.NextUpdate.UTC(),
+		RevokedCertificateEntries: []x509.RevocationListEntry{{
+			SerialNumber:   revoked.SerialNumber,
+			RevocationTime: opts.At.UTC(),
+			ReasonCode:     opts.Reason,
+		}},
+	}
+	// Ed25519 signing reads no randomness, so rand is never used.
+	der, err := x509.CreateRevocationList(rand.Reader, tmpl, issuer, key)
+	if err != nil {
+		return nil, err
+	}
+	return pem.EncodeToMemory(&pem.Block{Type: "X509 CRL", Bytes: der}), nil
+}
diff --git a/lisp2gov/repeal_test.go b/lisp2gov/repeal_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..437e9b652e4e447c4a6f1f77a01730648de03ce9
--- /dev/null
+++ b/lisp2gov/repeal_test.go
@@ -0,0 +1,103 @@
+package lisp2gov
+
+import (
+	"crypto/x509"
+	"encoding/pem"
+	"strings"
+	"testing"
+	"time"
+)
+
+var (
+	issued = time.Date(2027, 3, 1, 0, 0, 0, 0, time.UTC)
+	never  = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
+)
+
+func parseCRL(t *testing.T, data []byte) *x509.RevocationList {
+	t.Helper()
+	block, _ := pem.Decode(data)
+	if block == nil || block.Type != "X509 CRL" {
+		t.Fatalf("not an X509 CRL PEM block: %.40q", data)
+	}
+	crl, err := x509.ParseRevocationList(block.Bytes)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return crl
+}
+
+func TestRepealEachDepth(t *testing.T) {
+	out, err := Compile("(+ 1 (* 2 3))", Options{})
+	if err != nil {
+		t.Fatal(err)
+	}
+	certs := parsePEM(t, out)
+	for depth := 1; depth < len(certs); depth++ {
+		data, err := Repeal(certs, depth, RepealOptions{Reason: Reasons["superseded"], At: issued, Issued: issued, NextUpdate: never})
+		if err != nil {
+			t.Fatalf("depth %d: %v", depth, err)
+		}
+		crl := parseCRL(t, data)
+		// The issuer of the repealed cert signs the CRL, not the anchor.
+		if err := crl.CheckSignatureFrom(certs[depth-1]); err != nil {
+			t.Errorf("depth %d: CRL does not verify against its issuer: %v", depth, err)
+		}
+		if depth > 1 {
+			if err := crl.CheckSignatureFrom(certs[0]); err == nil {
+				t.Errorf("depth %d: CRL verifies against the anchor too", depth)
+			}
+		}
+		if len(crl.RevokedCertificateEntries) != 1 {
+			t.Fatalf("depth %d: %d entries", depth, len(crl.RevokedCertificateEntries))
+		}
+		e := crl.RevokedCertificateEntries[0]
+		if e.SerialNumber.Cmp(certs[depth].SerialNumber) != 0 || e.ReasonCode != 4 || !e.RevocationTime.Equal(issued) {
+			t.Errorf("depth %d: entry serial %v reason %d time %v", depth, e.SerialNumber, e.ReasonCode, e.RevocationTime)
+		}
+		if !crl.ThisUpdate.Equal(issued) || !crl.NextUpdate.Equal(never) {
+			t.Errorf("depth %d: thisUpdate %v nextUpdate %v", depth, crl.ThisUpdate, crl.NextUpdate)
+		}
+	}
+}
+
+func TestRepealIsDeterministic(t *testing.T) {
+	out, _ := Compile("(+ 1 2)", Options{})
+	certs := parsePEM(t, out)
+	opts := RepealOptions{At: issued, Issued: issued, NextUpdate: never}
+	a, _ := Repeal(certs, 2, opts)
+	b, _ := Repeal(certs, 2, opts)
+	if string(a) != string(b) {
+		t.Error("two repeals with the same inputs differ")
+	}
+}
+
+func TestRepealRefusals(t *testing.T) {
+	out, _ := Compile("(+ 1 2)", Options{})
+	certs := parsePEM(t, out)
+	other := [32]byte{4}
+	ok := RepealOptions{At: issued, Issued: issued, NextUpdate: never}
+	tests := []struct {
+		name  string
+		depth int
+		opts  RepealOptions
+		want  string
+	}{
+		{"depth 0 is the anchor", 0, ok, "depths 1 to 2"},
+		{"depth past the bottom", 3, ok, "depths 1 to 2"},
+		{"someone else's key", 1, RepealOptions{Seed: &other, At: issued, Issued: issued, NextUpdate: never}, "did not compile"},
+		{"stale before it is issued", 1, RepealOptions{At: issued, Issued: issued, NextUpdate: issued}, "go stale"},
+	}
+	for _, tt := range tests {
+		_, err := Repeal(certs, tt.depth, tt.opts)
+		if err == nil || !strings.Contains(err.Error(), tt.want) {
+			t.Errorf("%s: %v, want %q", tt.name, err, tt.want)
+		}
+	}
+}
+
+func TestReasonNames(t *testing.T) {
+	names := ReasonNames()
+	if names[0] != "unspecified" || names[len(names)-1] != "aACompromise" || len(names) != 10 {
+		t.Errorf("ReasonNames = %v", names)
+	}
+}