2021-05-21 19:44:01 +00:00
|
|
|
// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved.
|
2020-09-16 14:19:51 +00:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
2020-09-14 15:34:41 +00:00
|
|
|
|
|
|
|
package testutil
|
|
|
|
|
|
|
|
import (
|
2021-05-21 19:44:01 +00:00
|
|
|
"crypto/tls"
|
2020-09-14 15:34:41 +00:00
|
|
|
"encoding/pem"
|
2021-05-21 19:44:01 +00:00
|
|
|
"errors"
|
|
|
|
"net"
|
2020-09-14 15:34:41 +00:00
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
2021-05-21 19:44:01 +00:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
2020-09-14 15:34:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// TLSTestServer starts a test server listening on a local port using a test CA. It returns the PEM CA bundle and the
|
|
|
|
// URL of the listening server. The lifetime of the server is bound to the provided *testing.T.
|
|
|
|
func TLSTestServer(t *testing.T, handler http.HandlerFunc) (caBundlePEM string, url string) {
|
|
|
|
t.Helper()
|
|
|
|
server := httptest.NewTLSServer(handler)
|
|
|
|
t.Cleanup(server.Close)
|
|
|
|
|
|
|
|
caBundle := string(pem.EncodeToMemory(&pem.Block{
|
|
|
|
Type: "CERTIFICATE",
|
|
|
|
Bytes: server.TLS.Certificates[0].Certificate[0],
|
|
|
|
}))
|
|
|
|
return caBundle, server.URL
|
|
|
|
}
|
2021-05-21 19:44:01 +00:00
|
|
|
|
|
|
|
func TLSTestServerWithCert(t *testing.T, handler http.HandlerFunc, certificate *tls.Certificate) (url string) {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
server := http.Server{
|
|
|
|
TLSConfig: &tls.Config{
|
|
|
|
Certificates: []tls.Certificate{*certificate},
|
|
|
|
MinVersion: tls.VersionTLS12,
|
|
|
|
},
|
|
|
|
Handler: handler,
|
|
|
|
}
|
|
|
|
|
|
|
|
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
2021-05-24 21:24:09 +00:00
|
|
|
serverShutdownChan := make(chan error)
|
2021-05-21 19:44:01 +00:00
|
|
|
go func() {
|
|
|
|
// Empty certFile and keyFile will use certs from Server.TLSConfig.
|
2021-05-24 21:24:09 +00:00
|
|
|
serverShutdownChan <- server.ServeTLS(l, "", "")
|
2021-05-21 19:44:01 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
t.Cleanup(func() {
|
|
|
|
_ = server.Close()
|
2021-05-24 21:24:09 +00:00
|
|
|
serveErr := <-serverShutdownChan
|
|
|
|
if !errors.Is(serveErr, http.ErrServerClosed) {
|
|
|
|
t.Log("Got an unexpected error while starting the fake http server!")
|
|
|
|
require.NoError(t, serveErr)
|
|
|
|
}
|
2021-05-21 19:44:01 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
return l.Addr().String()
|
|
|
|
}
|