government / lisp2gov / compile.go

@ af60bd0141acb3f5ffa6ea8e93d9b351b41c9420 | history


package lisp2gov

import (
	"crypto/x509"
	"fmt"
	"strings"

	"government/ast"
	"government/sexpr"
)

type Options struct {
	// Name is the program's name, written into every cert's subject as
	// O=<name>. It defaults to "program".
	Name string
	// Seed derives every signing key. nil means DefaultSeed, which is
	// public, so anyone can rebuild or forge the program.
	Seed *[32]byte
	// IncludeSource copies the Lisp source into the file's header. It is
	// off by default: the certs alone are the program, and the source
	// may hold comments or code the author does not want to publish.
	IncludeSource bool
}

// Compile turns Lisp source into the bytes of a .gov file. The same source
// and options always give the same bytes. A syntax error is returned as the
// reader's *sexpr.SyntaxError, so callers can report its position.
func Compile(src string, opts Options) ([]byte, error) {
	certs, err := compileCerts(src, opts)
	if err != nil {
		return nil, err
	}
	return encodePEM(header(src, opts.IncludeSource), certs), nil
}

func (o Options) name() string {
	if o.Name == "" {
		return "program"
	}
	return o.Name
}

func (o Options) seed() [32]byte {
	if o.Seed == nil {
		return DefaultSeed
	}
	return *o.Seed
}

// compileCerts builds the anchor and one cert per depth. Cert 1 lists the
// top-level forms; certs 2..n list only anyPolicy, so every node below
// depth 1 exists in the policy tree only because a mapping in the cert
// above names it.
func compileCerts(src string, opts Options) ([]*x509.Certificate, error) {
	datums, err := sexpr.ReadProgram(src)
	if err != nil {
		return nil, err
	}
	tree, err := ast.Build(datums)
	if err != nil {
		return nil, err
	}
	layers, err := ast.Layer(tree)
	if err != nil {
		return nil, err
	}

	name, seed := opts.name(), opts.seed()
	prev, err := newAnchor(seed, name)
	if err != nil {
		return nil, err
	}
	certs := []*x509.Certificate{prev.cert}
	n := layers.Depth()
	for i := 1; i <= n; i++ {
		policies, err := policiesFor(i, layers.Nodes[i-1])
		if err != nil {
			return nil, err
		}
		mappings, err := mappingsFor(layers.Edges[i-1])
		if err != nil {
			return nil, err
		}
		next, err := newCert(seed, name, i, i == n, policies, mappings, prev)
		if err != nil {
			return nil, fmt.Errorf("cert %d: %w", i, err)
		}
		certs = append(certs, next.cert)
		prev = next
	}
	return certs, nil
}

// policiesFor lists what cert i asserts. Cert 1 names every top-level
// node. Certs 2..n assert anyPolicy, which creates their nodes, and also
// name each node with a note: a node anyPolicy creates gets no qualifiers,
// but RFC 9618 handles named policies (step d.1) before anyPolicy (d.2),
// which skips a policy that already has a node, so the named entry and its
// note are the ones that stick.
func policiesFor(i int, nodes []*ast.Node) ([]policyInfo, error) {
	var policies []policyInfo
	if i > 1 {
		policies = append(policies, policyInfo{id: anyPolicy})
	}
	for _, n := range nodes {
		if i > 1 && n.Note == "" {
			continue
		}
		oid, err := n.OID()
		if err != nil {
			return nil, err
		}
		policies = append(policies, policyInfo{id: oid, note: n.Note})
	}
	return policies, nil
}

// header is the text above the first PEM block: nothing, or with
// IncludeSource the Lisp source. Readers ignore text outside PEM blocks, so
// the source can travel with the program. Every source line is indented,
// which also means no line of it can start a PEM block, even if the source
// happens to contain "-----BEGIN".
func header(src string, includeSource bool) string {
	if !includeSource {
		return ""
	}
	var b strings.Builder
	for _, line := range strings.Split(strings.TrimRight(src, "\n"), "\n") {
		if line == "" {
			b.WriteString("\n")
			continue
		}
		b.WriteString("    " + line + "\n")
	}
	b.WriteString("\n")
	return b.String()
}