government

commit badf8bb5a62b278affaa0a72163e965aeecae8b0

tree

parent:
0a6d0b45c9b0e3f50876896c1c597c24311ceb7b

nmyk <nick@nmyk.io>

2026-11-14T16:06:42-05:00

add internal/der for writing policy mappings

diff --git a/ast/oid.go b/ast/oid.go
index 9d5c42c9a38beb932e9e94be5b79ba8d92d7477d..04c5e52a43c9275f081cec86e19206349f55f9ba 100644
--- a/ast/oid.go
+++ b/ast/oid.go
@@ -7,6 +7,7 @@ 	"fmt"
 	"strings"
 	"unicode/utf8"
 
+	"government/internal/der"
 	"government/sexpr"
 )
 
@@ -76,10 +77,10 @@ 		}
 	}
 
 	b := append([]byte{}, rootBytes...)
-	b = appendArc(b, uint64(ns))
-	b = appendArc(b, id)
+	b = der.AppendArc(b, uint64(ns))
+	b = der.AppendArc(b, id)
 	for _, arc := range payload {
-		b = appendArc(b, arc)
+		b = der.AppendArc(b, arc)
 	}
 	var oid x509.OID
 	if err := oid.UnmarshalBinary(b); err != nil {
@@ -177,25 +178,6 @@ 	default:
 		return fmt.Errorf("unknown %s", ns)
 	}
 	return nil
-}
-
-// appendArc writes arc in base 128, high digits first, with the top bit set
-// on every byte but the last. This is how DER encodes each OID arc.
-func appendArc(b []byte, arc uint64) []byte {
-	var digits [10]byte
-	i := len(digits)
-	for {
-		i--
-		digits[i] = byte(arc & 0x7f)
-		arc >>= 7
-		if arc == 0 {
-			break
-		}
-	}
-	for j := i; j < len(digits)-1; j++ {
-		digits[j] |= 0x80
-	}
-	return append(b, digits[i:]...)
 }
 
 func readArcs(b []byte) ([]uint64, error) {
diff --git a/internal/der/der.go b/internal/der/der.go
new file mode 100644
index 0000000000000000000000000000000000000000..011c83d5b302fd941f2255ad0250600deef74226
--- /dev/null
+++ b/internal/der/der.go
@@ -0,0 +1,104 @@
+// Package der writes the few ASN.1 DER shapes GOVERNMENT needs for the
+// certificate extensions Go cannot produce itself.
+//
+// Every DER value is a TLV: a tag byte saying what it is, the length of its
+// content, and the content. DER is the one encoding of ASN.1 that allows
+// exactly one byte string per value, which is what makes a signature over
+// those bytes meaningful: a verifier re-encoding the same value gets the
+// same bytes.
+package der
+
+import (
+	"crypto/x509"
+	"errors"
+)
+
+// Tags used here. Bit 0x20 marks a constructed value, one whose content is
+// itself a series of TLVs.
+const (
+	TagOID        = 0x06
+	TagUTF8String = 0x0c
+	TagSequence   = 0x30
+)
+
+// TLV encodes one value. Lengths below 128 take one byte. Longer ones take
+// 0x80 plus a count of length bytes, then the length in big-endian with no
+// leading zeros; DER forbids every other way of writing a length.
+func TLV(tag byte, content []byte) []byte {
+	b := []byte{tag}
+	n := len(content)
+	if n < 0x80 {
+		b = append(b, byte(n))
+	} else {
+		var digits []byte
+		for ; n > 0; n >>= 8 {
+			digits = append([]byte{byte(n)}, digits...)
+		}
+		b = append(b, 0x80|byte(len(digits)))
+		b = append(b, digits...)
+	}
+	return append(b, content...)
+}
+
+func Sequence(elements ...[]byte) []byte {
+	var content []byte
+	for _, e := range elements {
+		content = append(content, e...)
+	}
+	return TLV(TagSequence, content)
+}
+
+func UTF8String(s string) []byte {
+	return TLV(TagUTF8String, []byte(s))
+}
+
+// OID encodes oid. x509.OID already holds the content bytes, which is the
+// only way to carry an arc wider than 64 bits such as the GOV root's.
+func OID(oid x509.OID) []byte {
+	content, err := oid.MarshalBinary()
+	if err != nil {
+		// MarshalBinary only reports an OID that was never set.
+		panic(err)
+	}
+	return TLV(TagOID, content)
+}
+
+// OIDContent encodes arcs as an OID's content bytes. The first two arcs
+// share one value, 40*first + second, which is why the first arc is
+// limited to 0, 1 or 2.
+func OIDContent(arcs ...uint64) ([]byte, error) {
+	if len(arcs) < 2 {
+		return nil, errors.New("an OID needs at least two arcs")
+	}
+	if arcs[0] > 2 || (arcs[0] < 2 && arcs[1] >= 40) {
+		return nil, errors.New("invalid first two arcs")
+	}
+	if arcs[0] == 2 && arcs[1] > (1<<64-1)-80 {
+		return nil, errors.New("second arc too large")
+	}
+	b := AppendArc(nil, arcs[0]*40+arcs[1])
+	for _, arc := range arcs[2:] {
+		b = AppendArc(b, arc)
+	}
+	return b, nil
+}
+
+// AppendArc writes one arc in base 128, high digits first, with the top bit
+// set on every byte but the last. That top bit is how a reader finds where
+// each arc ends.
+func AppendArc(b []byte, arc uint64) []byte {
+	var digits [10]byte
+	i := len(digits)
+	for {
+		i--
+		digits[i] = byte(arc & 0x7f)
+		arc >>= 7
+		if arc == 0 {
+			break
+		}
+	}
+	for j := i; j < len(digits)-1; j++ {
+		digits[j] |= 0x80
+	}
+	return append(b, digits[i:]...)
+}
diff --git a/internal/der/der_test.go b/internal/der/der_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..638a49f97138921042b1c52a44e3c013278f3b58
--- /dev/null
+++ b/internal/der/der_test.go
@@ -0,0 +1,140 @@
+package der
+
+import (
+	"bytes"
+	"crypto/x509"
+	"encoding/asn1"
+	"strings"
+	"testing"
+)
+
+func mustMarshal(t *testing.T, v any, params string) []byte {
+	t.Helper()
+	b, err := asn1.MarshalWithParams(v, params)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return b
+}
+
+func TestLengthForms(t *testing.T) {
+	// An OCTET STRING (tag 4) of each size, against encoding/asn1.
+	for _, n := range []int{0, 1, 127, 128, 255, 256, 65535, 65536, 1 << 24} {
+		content := bytes.Repeat([]byte{0xab}, n)
+		got := TLV(0x04, content)
+		want := mustMarshal(t, content, "")
+		if !bytes.Equal(got, want) {
+			t.Errorf("length %d: header % x, want % x", n, got[:min(len(got), 6)], want[:min(len(want), 6)])
+		}
+	}
+}
+
+func TestOIDContent(t *testing.T) {
+	tests := [][]uint64{
+		{1, 2},
+		{2, 5, 29, 32, 0}, // anyPolicy
+		{2, 5, 29, 33},    // policyMappings
+		{1, 3, 6, 1, 5, 5, 7, 2, 2},
+		{2, 999, 3}, // second arc past 40 under arc 2
+		{1, 2, 128, 16383, 16384, 1 << 63},
+	}
+	for _, arcs := range tests {
+		got, err := OIDContent(arcs...)
+		if err != nil {
+			t.Errorf("%v: %v", arcs, err)
+			continue
+		}
+		oid, err := x509.OIDFromInts(arcs)
+		if err != nil {
+			t.Fatal(err)
+		}
+		want, _ := oid.MarshalBinary()
+		if !bytes.Equal(got, want) {
+			t.Errorf("%v: % x, want % x (x509.OID)", arcs, got, want)
+		}
+		if !bytes.Equal(OID(oid), TLV(TagOID, got)) {
+			t.Errorf("%v: OID and OIDContent disagree", arcs)
+		}
+	}
+}
+
+func TestOIDMatchesASN1(t *testing.T) {
+	for _, arcs := range []asn1.ObjectIdentifier{{2, 5, 29, 32, 0}, {1, 3, 6, 1, 4, 1, 311}, {2, 999, 3}} {
+		oid, err := x509.ParseOID(arcs.String())
+		if err != nil {
+			t.Fatal(err)
+		}
+		if got, want := OID(oid), mustMarshal(t, arcs, ""); !bytes.Equal(got, want) {
+			t.Errorf("%v: % x, want % x", arcs, got, want)
+		}
+	}
+}
+
+func TestOIDWithLargeArc(t *testing.T) {
+	// encoding/asn1 cannot write arcs past int, so compare against
+	// x509.ParseOID, which can.
+	const s = "2.25.9665536045854453410170579537759926404.2.1.52.50"
+	oid, err := x509.ParseOID(s)
+	if err != nil {
+		t.Fatal(err)
+	}
+	enc := OID(oid)
+	var back x509.OID
+	if err := back.UnmarshalBinary(enc[2:]); err != nil || back.String() != s {
+		t.Errorf("round trip gave %s, %v", back, err)
+	}
+	if enc[0] != TagOID || int(enc[1]) != len(enc)-2 {
+		t.Errorf("header % x", enc[:2])
+	}
+}
+
+func TestOIDContentRejects(t *testing.T) {
+	for _, arcs := range [][]uint64{{1}, {3, 1}, {0, 40}, {1, 40}} {
+		if _, err := OIDContent(arcs...); err == nil {
+			t.Errorf("%v accepted", arcs)
+		}
+	}
+}
+
+func TestUTF8String(t *testing.T) {
+	for _, s := range []string{"", "hi", "héllo 😀", strings.Repeat("x", 200)} {
+		if got, want := UTF8String(s), mustMarshal(t, s, "utf8"); !bytes.Equal(got, want) {
+			t.Errorf("%q: % x, want % x", s, got, want)
+		}
+	}
+}
+
+// TestSequenceOfSequences builds the shape of PolicyMappings, a SEQUENCE OF
+// SEQUENCE { issuerDomainPolicy, subjectDomainPolicy }, both ways.
+func TestSequenceOfSequences(t *testing.T) {
+	type mapping struct {
+		Issuer, Subject asn1.ObjectIdentifier
+	}
+	pairs := []mapping{
+		{asn1.ObjectIdentifier{1, 2, 3}, asn1.ObjectIdentifier{1, 2, 4}},
+		{asn1.ObjectIdentifier{1, 2, 3}, asn1.ObjectIdentifier{1, 2, 5, 1000}},
+	}
+	var elems [][]byte
+	for _, p := range pairs {
+		i, _ := x509.ParseOID(p.Issuer.String())
+		s, _ := x509.ParseOID(p.Subject.String())
+		elems = append(elems, Sequence(OID(i), OID(s)))
+	}
+	if got, want := Sequence(elems...), mustMarshal(t, pairs, ""); !bytes.Equal(got, want) {
+		t.Errorf("% x\nwant % x", got, want)
+	}
+	if got, want := Sequence(), mustMarshal(t, []mapping{}, ""); !bytes.Equal(got, want) {
+		t.Errorf("empty: % x, want % x", got, want)
+	}
+}
+
+func TestMixedSequence(t *testing.T) {
+	v := struct {
+		ID   asn1.ObjectIdentifier
+		Text string `asn1:"utf8"`
+	}{asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 2}, strings.Repeat("note ", 40)}
+	oid, _ := x509.ParseOID(v.ID.String())
+	if got, want := Sequence(OID(oid), UTF8String(v.Text)), mustMarshal(t, v, ""); !bytes.Equal(got, want) {
+		t.Errorf("% x\nwant % x", got, want)
+	}
+}