government / lisp2gov / compile.go

@ 1e3679e075694dda43bb3b82dd39f993c8e7705a | history


package lisp2gov

import (
	"crypto/x509"
	"fmt"
	"net/mail"
	"strings"
	"time"

	"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
	// NoShare keeps every copy of a repeated subexpression. By default
	// identical lists at the same depth become one node with several
	// parents (see ast.Share), which only ever makes a program smaller.
	NoShare bool
	// Author is who ratifies the program, as "Name <email>", "Name" or
	// "email". The name goes in the anchor's subject and the email in its
	// subjectAltName. It is only a claim unless Seed is the author's own
	// key: anyone can type a name, but only the key holder can sign.
	Author string
	// Effective and Expires bound when the program is in force, on every
	// cert. Zero values mean 2000-01-01 and 9999-12-31 23:59:59, RFC
	// 5280's "no well-defined expiration".
	Effective, Expires time.Time
}

// 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) profile() (profile, error) {
	p := profile{seed: DefaultSeed, program: o.name(), notBefore: defaultEffective, notAfter: defaultExpires}
	if o.Seed != nil {
		p.seed = *o.Seed
	}
	if !o.Effective.IsZero() {
		p.notBefore = o.Effective.UTC()
	}
	if !o.Expires.IsZero() {
		p.notAfter = o.Expires.UTC()
	}
	if !p.notBefore.Before(p.notAfter) {
		return profile{}, fmt.Errorf("the program would expire (%s) before it takes effect (%s)",
			p.notAfter.Format(time.RFC3339), p.notBefore.Format(time.RFC3339))
	}
	var err error
	if p.author, p.email, err = parseAuthor(o.Author); err != nil {
		return profile{}, err
	}
	return p, nil
}

// parseAuthor splits "Ada Lovelace <ada@example.com>" into its name and
// email. A bare name or a bare email is allowed too.
func parseAuthor(s string) (name, email string, err error) {
	s = strings.TrimSpace(s)
	if s == "" {
		return "", "", nil
	}
	if !strings.ContainsAny(s, "<@") {
		return s, "", nil
	}
	addr, err := mail.ParseAddress(s)
	if err != nil {
		return "", "", fmt.Errorf("author %q: want \"Name <email>\", a name or an email", s)
	}
	if addr.Name == "" {
		return addr.Address, addr.Address, nil
	}
	return addr.Name, addr.Address, nil
}

// 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
	}
	if !opts.NoShare {
		tree = ast.Share(tree)
	}
	layers, err := ast.Layer(tree)
	if err != nil {
		return nil, err
	}

	p, err := opts.profile()
	if err != nil {
		return nil, err
	}
	prev, err := newAnchor(p)
	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(p, 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()
}