summaryrefslogtreecommitdiff
path: root/internal/test
diff options
context:
space:
mode:
authorjwijenbergh <jeroenwijenbergh@protonmail.com>2023-02-16 15:48:20 +0100
committerjwijenbergh <jeroenwijenbergh@protonmail.com>2023-02-16 15:48:20 +0100
commitf718788442682f87e2fd1b6067f6062bade52d52 (patch)
treee3f2adc39efbdb51233eb45f2897a88e3157def2 /internal/test
parent2a46b5771d15ea55e20a5b52bddb6c04b55326e7 (diff)
Test: Implement util package for starting a TLS server
Diffstat (limited to 'internal/test')
-rw-r--r--internal/test/server.go44
1 files changed, 44 insertions, 0 deletions
diff --git a/internal/test/server.go b/internal/test/server.go
new file mode 100644
index 0000000..6426db0
--- /dev/null
+++ b/internal/test/server.go
@@ -0,0 +1,44 @@
+// Package test implements utilities for testing
+package test
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "net/http"
+ "net/http/httptest"
+ httpw "github.com/eduvpn/eduvpn-common/internal/http"
+ "github.com/go-errors/errors"
+)
+
+type TestServer struct {
+ *httptest.Server
+}
+
+func NewServer(handler http.Handler) *TestServer {
+ s := httptest.NewTLSServer(handler)
+
+ return &TestServer{s}
+}
+
+// Client returns a test client that trusts the HTTPS certificates
+func (srv *TestServer) Client() (*httpw.Client, error) {
+ // Get the certs from the test server
+ certs := x509.NewCertPool()
+ for _, c := range srv.TLS.Certificates {
+ roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
+ if err != nil {
+ return nil, errors.WrapPrefix(err, "failed to parse root certificate", 0)
+ }
+ for _, root := range roots {
+ certs.AddCert(root)
+ }
+ }
+ // Override the client such that it only trusts the test server cert
+ client := httpw.NewClient()
+ client.Client.Transport = &http.Transport{
+ TLSClientConfig: &tls.Config{
+ RootCAs: certs,
+ },
+ }
+ return client, nil
+}