government

commit 53308ffa01ed91d41c6657b16c77ee7a97ad8d3b

tree

parent:
bdd32d2bb7ca2a1b5b8c192fbaab691d8f1ed255

nmyk <nick@nmyk.io>

2026-11-14T17:05:46-05:00

add policy graph

diff --git a/policy/doc.go b/policy/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..e7bc9b29a15284a656c6c6c663d2670f96c937b1
--- /dev/null
+++ b/policy/doc.go
@@ -0,0 +1,5 @@
+// Package policy runs RFC 5280 certificate policy processing, in the graph
+// form RFC 9618 defines, over a ratified chain. The graph it builds is the
+// program: each node is one AST node's OID, and each edge is a parent->child
+// link.
+package policy
diff --git a/policy/error.go b/policy/error.go
new file mode 100644
index 0000000000000000000000000000000000000000..7e1ab3cada1bbc783a2fd8a327af8384d744c720
--- /dev/null
+++ b/policy/error.go
@@ -0,0 +1,18 @@
+package policy
+
+import "fmt"
+
+// ErrPolicy: policy processing rejected the chain, so the certs do not
+// describe a program.
+const ErrPolicy = "E-POLICY"
+
+type Error struct {
+	Code string
+	Msg  string
+}
+
+func (e *Error) Error() string { return e.Code + ": " + e.Msg }
+
+func errorf(code, format string, args ...any) *Error {
+	return &Error{Code: code, Msg: fmt.Sprintf(format, args...)}
+}
diff --git a/policy/graph.go b/policy/graph.go
new file mode 100644
index 0000000000000000000000000000000000000000..6c1765a2883a81ef87804e8e20447f81692b8189
--- /dev/null
+++ b/policy/graph.go
@@ -0,0 +1,175 @@
+package policy
+
+import (
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/asn1"
+	"slices"
+)
+
+var (
+	// AnyPolicy is the wildcard: a cert asserting it accepts whatever its
+	// issuer's nodes expect.
+	AnyPolicy = mustOID("2.5.29.32.0")
+
+	oidCertificatePolicies = asn1.ObjectIdentifier{2, 5, 29, 32}
+)
+
+func mustOID(s string) x509.OID {
+	oid, err := x509.ParseOID(s)
+	if err != nil {
+		panic(err)
+	}
+	return oid
+}
+
+// Node is one node of the valid policy graph: a policy that holds along
+// the path from the root down to its depth.
+type Node struct {
+	Policy x509.OID
+	Depth  int
+	// RFC 9618 lets a node have several parents, where RFC 5280's tree
+	// would have copied it under each one.
+	Parents  []*Node
+	Children []*Node
+	// Expected is the expected_policy_set: the policies the next cert may
+	// assert under this node. It is the node's own policy unless a mapping
+	// replaces it.
+	Expected []x509.OID
+}
+
+func (n *Node) expects(p x509.OID) bool {
+	return slices.ContainsFunc(n.Expected, p.Equal)
+}
+
+// Graph is the valid policy graph after the whole path. Levels[0] holds the
+// root, an anyPolicy node; Levels[i] holds the nodes made by cert i.
+type Graph struct {
+	Levels [][]*Node
+}
+
+func (g *Graph) Depth() int { return len(g.Levels) - 1 }
+
+// Process runs policy processing over a ratified chain, anchor first. The
+// anchor is the trust anchor, not part of the path, so the path is
+// certs[1:], and cert i is certs[i].
+//
+// The inputs are fixed by the design: user-initial-policy-set {anyPolicy},
+// explicit policy required, anyPolicy and mappings not inhibited. Ratify
+// already rejected policyConstraints and inhibitAnyPolicy, so the RFC's
+// three counters never reach zero and are left out.
+func Process(certs []*x509.Certificate) (*Graph, error) {
+	root := &Node{Policy: AnyPolicy, Expected: []x509.OID{AnyPolicy}}
+	g := &Graph{Levels: [][]*Node{{root}}}
+	for i := 1; i < len(certs); i++ {
+		if err := g.addCert(i, certs[i]); err != nil {
+			return nil, err
+		}
+	}
+	return g, nil
+}
+
+// addCert is RFC 5280 6.1.3 (d)-(f) for cert i, in RFC 9618's graph form.
+func (g *Graph) addCert(i int, c *x509.Certificate) error {
+	// (e): a cert with no certificatePolicies extension empties the graph,
+	// and (f): with explicit policy required, an empty graph is a failure.
+	if !hasExtension(c, oidCertificatePolicies) {
+		return errorf(ErrPolicy, "cert %d has no certificatePolicies, so no policy holds past depth %d", i, i-1)
+	}
+	parents := g.Levels[i-1]
+	var level []*Node
+	byPolicy := map[string]*Node{}
+	add := func(p x509.OID, from []*Node) {
+		n := &Node{Policy: p, Depth: i, Parents: from, Expected: []x509.OID{p}}
+		for _, parent := range from {
+			parent.Children = append(parent.Children, n)
+		}
+		level = append(level, n)
+		byPolicy[key(p)] = n
+	}
+	expecting := func(p x509.OID) []*Node {
+		var from []*Node
+		for _, parent := range parents {
+			if parent.expects(p) {
+				from = append(from, parent)
+			}
+		}
+		return from
+	}
+
+	// (d)(1): each policy the cert names goes under every node that
+	// expects it, or failing that under an anyPolicy node. A policy with
+	// neither is dropped without a word; the strict check catches that.
+	assertsAny := false
+	for _, p := range c.Policies {
+		if p.Equal(AnyPolicy) {
+			assertsAny = true
+			continue
+		}
+		if byPolicy[key(p)] != nil {
+			continue
+		}
+		from := expecting(p)
+		if len(from) == 0 {
+			for _, parent := range parents {
+				if parent.Policy.Equal(AnyPolicy) {
+					from = append(from, parent)
+				}
+			}
+		}
+		if len(from) > 0 {
+			add(p, from)
+		}
+	}
+
+	// (d)(2), RFC 9618's form: anyPolicy in the cert creates every policy
+	// some parent expects that has no node yet. This is the rule that lets
+	// certs 2..n list nothing but anyPolicy: it creates each mapped child,
+	// and copies down each atom that expects only itself.
+	if assertsAny {
+		for _, parent := range parents {
+			for _, p := range parent.Expected {
+				if byPolicy[key(p)] == nil {
+					add(p, expecting(p))
+				}
+			}
+		}
+	}
+
+	g.Levels = append(g.Levels, level)
+	g.prune(i)
+	if len(level) == 0 {
+		return errorf(ErrPolicy, "no policy holds at depth %d: cert %d asserts nothing its issuer expects", i, i)
+	}
+	return nil
+}
+
+// prune is (d)(3): delete every node at depth i-1 or above that has no
+// children, repeatedly, since each deletion can leave its parents
+// childless. Going up one level at a time does it in one pass.
+func (g *Graph) prune(i int) {
+	for d := i - 1; d >= 0; d-- {
+		kept := g.Levels[d][:0]
+		for _, n := range g.Levels[d] {
+			if len(n.Children) > 0 {
+				kept = append(kept, n)
+				continue
+			}
+			for _, parent := range n.Parents {
+				parent.Children = slices.DeleteFunc(parent.Children, func(c *Node) bool { return c == n })
+			}
+		}
+		g.Levels[d] = kept
+	}
+}
+
+func hasExtension(c *x509.Certificate, id asn1.ObjectIdentifier) bool {
+	return slices.ContainsFunc(c.Extensions, func(e pkix.Extension) bool { return e.Id.Equal(id) })
+}
+
+// key makes an OID usable as a map key. x509.OID is a byte slice inside,
+// so it cannot be one directly.
+func key(oid x509.OID) string {
+	b, _ := oid.MarshalBinary()
+	return string(b)
+}
diff --git a/policy/graph_test.go b/policy/graph_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f1e1966414de83d9f814bf528792d5d89bef5dfc
--- /dev/null
+++ b/policy/graph_test.go
@@ -0,0 +1,152 @@
+package policy
+
+import (
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"errors"
+	"strings"
+	"testing"
+	"time"
+
+	"government/lisp2gov"
+	"government/ratify"
+)
+
+// fakeCert carries only what policy processing reads. Signatures and names
+// are ratify's job, so these certs need neither.
+func fakeCert(policies ...string) *x509.Certificate {
+	c := &x509.Certificate{Extensions: []pkix.Extension{{Id: oidCertificatePolicies}}}
+	for _, p := range policies {
+		if p == "any" {
+			p = "2.5.29.32.0"
+		}
+		c.Policies = append(c.Policies, mustOID(p))
+	}
+	return c
+}
+
+// path prepends a stand-in anchor, which Process skips.
+func path(certs ...*x509.Certificate) []*x509.Certificate {
+	return append([]*x509.Certificate{{}}, certs...)
+}
+
+// levels prints each depth's policies, e.g. "any | 1.2.3 1.2.4 | 1.2.3".
+func levels(g *Graph) string {
+	var parts []string
+	for _, level := range g.Levels {
+		var names []string
+		for _, n := range level {
+			name := n.Policy.String()
+			if n.Policy.Equal(AnyPolicy) {
+				name = "any"
+			}
+			names = append(names, name)
+		}
+		parts = append(parts, strings.Join(names, " "))
+	}
+	return strings.Join(parts, " | ")
+}
+
+func mustProcess(t *testing.T, certs []*x509.Certificate) *Graph {
+	t.Helper()
+	g, err := Process(certs)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return g
+}
+
+func wantPolicyError(t *testing.T, name string, certs []*x509.Certificate, msg string) {
+	t.Helper()
+	_, err := Process(certs)
+	var e *Error
+	if !errors.As(err, &e) || e.Code != ErrPolicy || !strings.Contains(e.Msg, msg) {
+		t.Errorf("%s: error = %v, want %s containing %q", name, err, ErrPolicy, msg)
+	}
+}
+
+func TestSamePolicyHolds(t *testing.T) {
+	g := mustProcess(t, path(fakeCert("1.2.3"), fakeCert("1.2.3"), fakeCert("1.2.3")))
+	if got, want := levels(g), "any | 1.2.3 | 1.2.3 | 1.2.3"; got != want {
+		t.Errorf("levels = %s, want %s", got, want)
+	}
+	for d := 1; d <= 3; d++ {
+		n := g.Levels[d][0]
+		if len(n.Parents) != 1 || n.Parents[0] != g.Levels[d-1][0] {
+			t.Errorf("depth %d: parent is not the node above", d)
+		}
+	}
+}
+
+func TestDroppedPolicyFails(t *testing.T) {
+	wantPolicyError(t, "a cert asserts something else", path(fakeCert("1.2.3"), fakeCert("1.2.4"), fakeCert("1.2.3")),
+		"no policy holds at depth 2")
+	noExtension := &x509.Certificate{}
+	wantPolicyError(t, "a cert has no certificatePolicies", path(fakeCert("1.2.3"), noExtension),
+		"cert 2 has no certificatePolicies")
+}
+
+func TestPruneDeadEndBranch(t *testing.T) {
+	// 1.2.4 holds at depth 1 but nothing continues it at depth 2, so it is
+	// pruned: it does not hold along the whole path.
+	g := mustProcess(t, path(fakeCert("1.2.3", "1.2.4"), fakeCert("1.2.3"), fakeCert("1.2.3")))
+	if got, want := levels(g), "any | 1.2.3 | 1.2.3 | 1.2.3"; got != want {
+		t.Errorf("levels = %s, want %s", got, want)
+	}
+	if n := len(g.Levels[0][0].Children); n != 1 {
+		t.Errorf("root has %d children after pruning, want 1", n)
+	}
+}
+
+func TestPruningCascades(t *testing.T) {
+	// 1.2.4 survives cert 2 but not cert 3; its node at depth 2 goes, and
+	// then its now childless node at depth 1.
+	g := mustProcess(t, path(fakeCert("1.2.3", "1.2.4"), fakeCert("1.2.3", "1.2.4"), fakeCert("1.2.3")))
+	if got, want := levels(g), "any | 1.2.3 | 1.2.3 | 1.2.3"; got != want {
+		t.Errorf("levels = %s, want %s", got, want)
+	}
+}
+
+// TestAnyPolicyCopiesAtoms are the design-phase prototype's copyonly and
+// nocopy chains: an atom listed only in cert 1 reaches depth 3 when certs 2
+// and 3 assert anyPolicy, and is pruned away when they do not.
+func TestAnyPolicyCopiesAtoms(t *testing.T) {
+	g := mustProcess(t, path(fakeCert("1.2.3"), fakeCert("any"), fakeCert("any")))
+	if got, want := levels(g), "any | 1.2.3 | 1.2.3 | 1.2.3"; got != want {
+		t.Errorf("copyonly: levels = %s, want %s", got, want)
+	}
+	wantPolicyError(t, "nocopy", path(fakeCert("1.2.3"), fakeCert("1.2.9"), fakeCert("1.2.9")), "no policy holds at depth 2")
+}
+
+func TestAnyPolicyAtDepthOneAdoptsAnything(t *testing.T) {
+	// In real PKI an intermediate asserting anyPolicy accepts whatever the
+	// next cert names: the policy has no node expecting it, so it goes
+	// under the anyPolicy node.
+	g := mustProcess(t, path(fakeCert("any"), fakeCert("1.2.3")))
+	if got, want := levels(g), "any | any | 1.2.3"; got != want {
+		t.Errorf("levels = %s, want %s", got, want)
+	}
+}
+
+var ratifyTime = time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
+
+func TestCompiledDepthOnePrograms(t *testing.T) {
+	src := `1 "two" 3.0 x`
+	out, err := lisp2gov.Compile(src, lisp2gov.Options{})
+	if err != nil {
+		t.Fatal(err)
+	}
+	certs, err := ratify.Ratify(out, ratify.Options{At: ratifyTime})
+	if err != nil {
+		t.Fatal(err)
+	}
+	g := mustProcess(t, certs)
+	if g.Depth() != 1 || len(g.Levels[1]) != 4 {
+		t.Fatalf("levels = %s", levels(g))
+	}
+	for i, n := range g.Levels[1] {
+		if !n.Policy.Equal(certs[1].Policies[i]) {
+			t.Errorf("node %d is %s, want %s", i, n.Policy, certs[1].Policies[i])
+		}
+	}
+}