summaryrefslogtreecommitdiff
path: root/internal/test/server.go
blob: e020d6994f9a6b46930f758e53754572c8c1f0e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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 Server struct {
	*httptest.Server
}

func NewServer(handler http.Handler) *Server {
	s := httptest.NewTLSServer(handler)

	return &Server{s}
}

// Client returns a test client that trusts the HTTPS certificates
func (srv *Server) 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
}