2022-08-24 21:45:55 +00:00
|
|
|
// Copyright 2020-2022 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"
|
|
|
|
"errors"
|
|
|
|
"net"
|
2020-09-14 15:34:41 +00:00
|
|
|
"net/http"
|
|
|
|
"testing"
|
2022-08-24 21:45:55 +00:00
|
|
|
"time"
|
2021-05-21 19:44:01 +00:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
2021-10-20 11:59:24 +00:00
|
|
|
|
|
|
|
"go.pinniped.dev/internal/crypto/ptls"
|
|
|
|
"go.pinniped.dev/internal/testutil/tlsserver"
|
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.
|
2021-10-20 11:59:24 +00:00
|
|
|
func TLSTestServer(t *testing.T, handler http.HandlerFunc) (caBundlePEM, url string) {
|
2020-09-14 15:34:41 +00:00
|
|
|
t.Helper()
|
2021-10-20 11:59:24 +00:00
|
|
|
|
|
|
|
server := tlsserver.TLSTestServer(t, handler, nil)
|
|
|
|
|
|
|
|
return string(tlsserver.TLSTestServerCA(server)), server.URL
|
2020-09-14 15:34:41 +00:00
|
|
|
}
|
2021-05-21 19:44:01 +00:00
|
|
|
|
|
|
|
func TLSTestServerWithCert(t *testing.T, handler http.HandlerFunc, certificate *tls.Certificate) (url string) {
|
|
|
|
t.Helper()
|
|
|
|
|
2021-10-20 11:59:24 +00:00
|
|
|
c := ptls.Default(nil) // mimic API server config
|
|
|
|
c.Certificates = []tls.Certificate{*certificate}
|
|
|
|
|
2021-05-21 19:44:01 +00:00
|
|
|
server := http.Server{
|
2022-08-24 21:45:55 +00:00
|
|
|
TLSConfig: c,
|
|
|
|
Handler: handler,
|
|
|
|
ReadHeaderTimeout: 10 * time.Second,
|
2021-05-21 19:44:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
|
|
|
}
|