GitHub - madflojo/testcerts: Dynamically generate self-signed certificates and certificate authorities for Go tests

GitHub

2 min read Original article ↗

Actions Status codecov Go Report Card Go Reference license

Stop saving test certificates in your code repos. Start generating them in your tests.

func TestFunc(t *testing.T) {
	// Create and write self-signed Certificate and Key to temporary files
	cert, key, err := testcerts.GenerateCertsToTempFile("/tmp/")
	if err != nil {
		// do something
	}
	defer os.Remove(key)
	defer os.Remove(cert)

	// Start HTTP Listener with test certificates
	err = http.ListenAndServeTLS("127.0.0.1:443", cert, key, someHandler)
	if err != nil {
		// do something
	}
}

For more complex tests, you can also use this package to create a Certificate Authority and a key pair signed by that Certificate Authority for any test domain you want.

func TestFunc(t *testing.T) {
	// Generate Certificate Authority
	ca := testcerts.NewCA()

	// Create a signed Certificate and Key for "localhost"
	certs, err := ca.NewKeyPair("localhost")
	if err != nil {
		// do something
	}

	// Write certificates to a file
	err = certs.ToFile("/tmp/cert", "/tmp/key")
	if err != nil {
		// do something
	}

	// Start HTTP Listener
	go func() {
		if err := http.ListenAndServeTLS("localhost:443", "/tmp/cert", "/tmp/key", someHandler); err != nil {
			// do something
		}
	}()

	// Create a client with the self-signed CA
	tlsConfig, cfgErr := certs.ConfigureTLSConfig(ca.GenerateTLSConfig())
	if cfgErr != nil {
		// do something
	}

	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: tlsConfig,
		},
	}

	// Make an HTTPS request
	_, _ = client.Get("https://localhost")
}

KeyPairConfig supports additional certificate options. Set Expired when a test needs a certificate whose NotAfter time is already in the past.

func TestExpiredCertificate(t *testing.T) {
	ca := testcerts.NewCA()
	certs, err := ca.NewKeyPairFromConfig(testcerts.KeyPairConfig{
		Domains: []string{"localhost"},
		Expired: true,
	})
	if err != nil {
		t.Fatal(err)
	}
	if !certs.Cert().NotAfter.Before(time.Now()) {
		t.Fatal("expected an expired certificate")
	}
}

Simplify your testing, and don't hassle with certificates anymore.

Releases

Releases are managed by Release Please. Use Conventional Commits for changes merged to main; releasable commits create or update a release pull request with a generated changelog. Merging that pull request publishes the corresponding version tag and GitHub release.

Contributing

If you find a bug or have an idea for a feature, please open an issue or a pull request.

License

testcerts is released under the MIT License. See LICENSE for details.