-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
85 lines (66 loc) · 1.79 KB
/
main_test.go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMTLS(t *testing.T) {
caBundle, err := generateCACert("CA")
require.NoError(t, err)
serverBundle, err := generateServerCert(CertConfig{
CommonName: "mtls.dev",
Hosts: "127.0.0.1",
CACert: caBundle.Cert,
CAKey: caBundle.Key,
})
require.NoError(t, err)
clientBundle, err := generateServerCert(CertConfig{
CommonName: "mtls.dev",
CACert: caBundle.Cert,
CAKey: caBundle.Key,
})
require.NoError(t, err)
serverTLSConf := getTLSConfig(t, serverBundle.Cert, serverBundle.Key, caBundle.Cert, true)
srv := newTestServer(t, serverTLSConf)
defer srv.Close()
clientTLSConf := getTLSConfig(t, clientBundle.Cert, clientBundle.Key, caBundle.Cert, false)
client := srv.Client()
client.Transport = &http.Transport{
TLSClientConfig: clientTLSConf,
}
resp, err := client.Get(srv.URL)
require.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, []byte("hi!\n"), body)
}
func getTLSConfig(t *testing.T, cert, key, caCert []byte, isServer bool) *tls.Config {
pair, err := tls.X509KeyPair(cert, key)
require.NoError(t, err)
conf := &tls.Config{
Certificates: []tls.Certificate{pair},
}
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(caCert)
if isServer {
conf.ClientCAs = certPool
} else {
conf.RootCAs = certPool
}
conf.BuildNameToCertificate()
return conf
}
func newTestServer(t *testing.T, tlsConf *tls.Config) *httptest.Server {
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hi!")
}))
ts.TLS = tlsConf
ts.StartTLS()
return ts
}