Skip to content

Commit

Permalink
Generate test TLS certificates on demand
Browse files Browse the repository at this point in the history
This avoids having pem files that could expire and cause tests to
randomly start failing.

This makes tests slower, but computers are faster in 2025. If things are
really bad, we could refactor to use TestMain and make one certificate
rather than generating it on demand for tests, but I suspect this won't
be necessary.

Closes #1112.
  • Loading branch information
fsouza committed Feb 18, 2025
1 parent 9e09969 commit 911724f
Show file tree
Hide file tree
Showing 11 changed files with 157 additions and 135 deletions.
5 changes: 0 additions & 5 deletions build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,6 @@ func TestBuildImageContextDirDockerignoreParsing(t *testing.T) {
".dockerignore",
"Dockerfile",
"barfile",
"ca.pem",
"cert.pem",
"key.pem",
"server.pem",
"serverkey.pem",
"symlink",
}

Expand Down
12 changes: 8 additions & 4 deletions client_stress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import (
"sync"
"testing"
"time"

"github.com/fsouza/go-dockerclient/internal/testutils"
)

func TestClientDoConcurrentStress(t *testing.T) {
Expand All @@ -28,7 +30,7 @@ func TestClientDoConcurrentStress(t *testing.T) {
mu.Unlock()
})
var nativeSrvs []*httptest.Server
for i := 0; i < 3; i++ {
for range 3 {
srv, cleanup, err := newNativeServer(handler)
if err != nil {
t.Fatal(err)
Expand All @@ -54,6 +56,8 @@ func TestClientDoConcurrentStress(t *testing.T) {
for _, tt := range tests {
tt := tt
t.Run(tt.testCase, func(t *testing.T) {
_, serverCert := testutils.GenCertificate(t)

reqs = nil
var client *Client
var err error
Expand All @@ -65,11 +69,11 @@ func TestClientDoConcurrentStress(t *testing.T) {
}
defer tt.srv.Close()
if tt.withTLSClient {
certPEMBlock, certErr := os.ReadFile("testing/data/cert.pem")
certPEMBlock, certErr := os.ReadFile(serverCert.CertPath)
if certErr != nil {
t.Fatal(certErr)
}
keyPEMBlock, certErr := os.ReadFile("testing/data/key.pem")
keyPEMBlock, certErr := os.ReadFile(serverCert.KeyPath)
if certErr != nil {
t.Fatal(certErr)
}
Expand All @@ -88,7 +92,7 @@ func TestClientDoConcurrentStress(t *testing.T) {
var paths []string
errsCh := make(chan error, 3*n)
waiters := make(chan CloseWaiter, n)
for i := 0; i < n; i++ {
for i := range n {
path := fmt.Sprintf("/%05d", i)
paths = append(paths, http.MethodGet+path)
paths = append(paths, http.MethodPost+path)
Expand Down
13 changes: 9 additions & 4 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"testing"
"time"

"github.com/fsouza/go-dockerclient/internal/testutils"
"golang.org/x/term"
)

Expand Down Expand Up @@ -187,9 +188,11 @@ func TestNewTLSVersionedClientNoClientCert(t *testing.T) {

func TestNewTLSVersionedClientInvalidCA(t *testing.T) {
t.Parallel()
certPath := "testing/data/cert.pem"
keyPath := "testing/data/key.pem"
caPath := "testing/data/key.pem"
_, serverCert := testutils.GenCertificate(t)

certPath := serverCert.CertPath
keyPath := serverCert.KeyPath
caPath := serverCert.KeyPath
endpoint := "https://localhost:4243"
_, err := NewVersionedTLSClient(endpoint, certPath, keyPath, caPath, "1.14")
if err == nil {
Expand All @@ -199,9 +202,11 @@ func TestNewTLSVersionedClientInvalidCA(t *testing.T) {

func TestNewTLSVersionedClientInvalidCANoClientCert(t *testing.T) {
t.Parallel()
_, serverCert := testutils.GenCertificate(t)

certPath := "testing/data/cert_doesnotexist.pem"
keyPath := "testing/data/key_doesnotexist.pem"
caPath := "testing/data/key.pem"
caPath := serverCert.KeyPath
endpoint := "https://localhost:4243"
_, err := NewVersionedTLSClient(endpoint, certPath, keyPath, caPath, "1.14")
if err == nil {
Expand Down
7 changes: 5 additions & 2 deletions event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"testing"
"time"

"github.com/fsouza/go-dockerclient/internal/testutils"
"github.com/google/go-cmp/cmp"
)

Expand All @@ -25,15 +26,17 @@ func TestEventListeners(t *testing.T) {

func TestTLSEventListeners(t *testing.T) {
t.Parallel()
caCert, serverCert := testutils.GenCertificate(t)

testEventListeners("TestTLSEventListeners", t, func(handler http.Handler) *httptest.Server {
server := httptest.NewUnstartedServer(handler)

cert, err := tls.LoadX509KeyPair("testing/data/server.pem", "testing/data/serverkey.pem")
cert, err := tls.LoadX509KeyPair(serverCert.CertPath, serverCert.KeyPath)
if err != nil {
t.Fatalf("Error loading server key pair: %s", err)
}

caCert, err := os.ReadFile("testing/data/ca.pem")
caCert, err := os.ReadFile(caCert.CertPath)
if err != nil {
t.Fatalf("Error loading ca certificate: %s", err)
}
Expand Down
129 changes: 129 additions & 0 deletions internal/testutils/tls.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package testutils

import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"path/filepath"
"testing"
"time"
)

type Certificate struct {
CertPath string
KeyPath string
}

func newCertificate(parentDir string, kind string, cert *x509.Certificate, key *ecdsa.PrivateKey) (Certificate, error) {
certPath := filepath.Join(parentDir, kind+"-cert.pem")
certFile, err := os.Create(certPath)
if err != nil {
return Certificate{}, err
}
defer certFile.Close()

err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
if err != nil {
return Certificate{}, err
}

keyPath := filepath.Join(parentDir, kind+"-key.pem")
keyFile, err := os.Create(keyPath)
if err != nil {
return Certificate{}, err
}
defer keyFile.Close()

privBytes, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return Certificate{}, err
}
pem.Encode(keyFile, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})

return Certificate{
CertPath: certPath,
KeyPath: keyPath,
}, nil
}

func GenCertificate(t *testing.T) (ca Certificate, server Certificate) {
caCert, caKey, err := generateCA()
if err != nil {
t.Fatal(err)
}

privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}

template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{Organization: []string{"Example Inc"}},
DNSNames: []string{"example.com", "www.example.com"},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}

certBytes, err := x509.CreateCertificate(rand.Reader, &template, caCert, &privateKey.PublicKey, caKey)
if err != nil {
t.Fatal(err)
}

serverCert, err := x509.ParseCertificate(certBytes)
if err != nil {
t.Fatal(err)
}

ca, err = newCertificate(t.TempDir(), "ca", caCert, caKey)
if err != nil {
t.Fatal(err)
}

server, err = newCertificate(t.TempDir(), "server", serverCert, privateKey)
if err != nil {
t.Fatal(err)
}

return ca, server
}

func generateCA() (*x509.Certificate, *ecdsa.PrivateKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}

template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Test CA"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
BasicConstraintsValid: true,
IsCA: true,
MaxPathLen: 1,
}

certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return nil, nil, err
}

cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, nil, err
}

return cert, privateKey, nil
}
23 changes: 0 additions & 23 deletions testing/data/ca.pem

This file was deleted.

20 changes: 0 additions & 20 deletions testing/data/cert.pem

This file was deleted.

27 changes: 0 additions & 27 deletions testing/data/key.pem

This file was deleted.

20 changes: 0 additions & 20 deletions testing/data/server.pem

This file was deleted.

27 changes: 0 additions & 27 deletions testing/data/serverkey.pem

This file was deleted.

Loading

0 comments on commit 911724f

Please sign in to comment.