government / ratify / load_test.go

@ ba5c700b731db728fea52ac3080b57fbe2ed37b9 | history


package ratify

import (
	"bytes"
	"crypto/ed25519"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"government/lisp2gov"
)

func compile(t *testing.T, src string, opts lisp2gov.Options) []byte {
	t.Helper()
	out, err := lisp2gov.Compile(src, opts)
	if err != nil {
		t.Fatal(err)
	}
	return out
}

func wantMalformed(t *testing.T, name string, data []byte, msg string) {
	t.Helper()
	_, err := Load(data)
	var e *Error
	if !errors.As(err, &e) || e.Code != ErrMalformed || !strings.Contains(e.Msg, msg) {
		t.Errorf("%s: error = %v, want %s containing %q", name, err, ErrMalformed, msg)
	}
}

func TestLoadCompiledPrograms(t *testing.T) {
	files, _ := filepath.Glob("../testdata/*.gov.lisp")
	examples, _ := filepath.Glob("../examples/*.gov.lisp")
	files = append(files, examples...)
	for _, file := range files {
		src, err := os.ReadFile(file)
		if err != nil {
			t.Fatal(err)
		}
		for _, withSource := range []bool{false, true} {
			data := compile(t, string(src), lisp2gov.Options{IncludeSource: withSource})
			certs, err := Load(data)
			if err != nil {
				t.Errorf("%s (source %v): %v", file, withSource, err)
				continue
			}
			if want := bytes.Count(data, []byte("-----BEGIN CERTIFICATE-----")); len(certs) != want {
				t.Errorf("%s: %d certs, want %d", file, len(certs), want)
			}
		}
	}
}

func TestLoadIgnoresTextBetweenBlocks(t *testing.T) {
	data := compile(t, "(+ 1 2)", lisp2gov.Options{})
	commented := "a comment before\n" + strings.ReplaceAll(string(data), "-----END CERTIFICATE-----\n", "-----END CERTIFICATE-----\nand one after each block\n")
	a, err := Load(data)
	if err != nil {
		t.Fatal(err)
	}
	b, err := Load([]byte(commented))
	if err != nil {
		t.Fatal(err)
	}
	for i := range a {
		if !bytes.Equal(a[i].Raw, b[i].Raw) {
			t.Errorf("cert %d differs", i)
		}
	}
}

// TestLoadReadsDERNotText re-wraps every block's base64 at a different line
// width. The text changes, the DER does not, so the same certs load and
// the signatures still check: they cover the DER, not the PEM text.
func TestLoadReadsDERNotText(t *testing.T) {
	data := compile(t, "(+ 1 2)", lisp2gov.Options{})
	orig, err := Load(data)
	if err != nil {
		t.Fatal(err)
	}
	var rewrapped bytes.Buffer
	for _, c := range orig {
		b64 := base64.StdEncoding.EncodeToString(c.Raw)
		rewrapped.WriteString("-----BEGIN CERTIFICATE-----\n")
		for len(b64) > 40 {
			rewrapped.WriteString(b64[:40] + "\n")
			b64 = b64[40:]
		}
		rewrapped.WriteString(b64 + "\n-----END CERTIFICATE-----\n")
	}
	if bytes.Equal(rewrapped.Bytes(), data) {
		t.Fatal("rewrapping did not change the text")
	}
	certs, err := Load(rewrapped.Bytes())
	if err != nil {
		t.Fatal(err)
	}
	for i := 1; i < len(certs); i++ {
		if err := certs[i].CheckSignatureFrom(certs[i-1]); err != nil {
			t.Errorf("cert %d: %v", i, err)
		}
	}
}

func TestLoadRejects(t *testing.T) {
	good := compile(t, "(+ 1 2)", lisp2gov.Options{})
	blocks := strings.SplitAfter(string(good), "-----END CERTIFICATE-----\n")
	blocks = blocks[:len(blocks)-1]

	_, key, _ := ed25519.GenerateKey(nil)
	pkcs8, _ := x509.MarshalPKCS8PrivateKey(key)
	keyBlock := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}))

	brokenMiddle := blocks[0] + strings.Replace(blocks[1], "M", "!", 1) + blocks[2]
	withHeaders := strings.Replace(string(good), "-----BEGIN CERTIFICATE-----\n", "-----BEGIN CERTIFICATE-----\nProc-Type: 4,ENCRYPTED\n\n", 1)
	badDER := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte{0x30, 0x03, 1, 2, 3}}))

	tests := []struct {
		name string
		data string
		msg  string
	}{
		{"private key block", string(good) + keyBlock, "is a PRIVATE KEY"},
		{"private key first", keyBlock + string(good), "block 0 is a PRIVATE KEY"},
		{"only the anchor", blocks[0], "1 certificates"},
		{"empty file", "", "0 certificates"},
		{"text only", "(+ 1 2)\n", "0 certificates"},
		{"corrupt base64 in the middle", brokenMiddle, "3 PEM blocks begin but only 2"},
		{"PEM headers", withHeaders, "has PEM headers"},
		{"not a certificate inside", blocks[0] + badDER, "block 1:"},
	}
	for _, tt := range tests {
		wantMalformed(t, tt.name, []byte(tt.data), tt.msg)
	}
}