-
Notifications
You must be signed in to change notification settings - Fork 115
/
tls_test.go
109 lines (87 loc) · 2.51 KB
/
tls_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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package server
import (
"fmt"
"path/filepath"
"testing"
"net/http"
"net/http/httptest"
"context"
"github.com/infobloxopen/atlas-app-toolkit/v2/server/testdata"
"github.com/infobloxopen/atlas-app-toolkit/v2/servertest"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
func getPEMFiles(t *testing.T) (rmFunc func(), cert, key, ca string) {
tempDir, rmFunc, err := server_test.WritePEMFiles("")
if err != nil {
t.Fatalf("Could not write PEM files: %s", err)
}
cert = filepath.Join(tempDir, "cert.pem")
key = filepath.Join(tempDir, "key.pem")
ca = filepath.Join(tempDir, "ca.pem")
return
}
func TestNewTLSConfig(t *testing.T) {
rmFunc, cert, key, ca := getPEMFiles(t)
defer rmFunc()
tlsConfig, err := NewTLSConfig(cert, key, ca)
if err != nil {
t.Fatalf("Failed to create TLSConfig: %s", err)
}
t.Run("can issue https request", func(t *testing.T) {
h := http.NewServeMux()
h.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) { writer.WriteHeader(204) })
s := httptest.NewUnstartedServer(h)
s.TLS = tlsConfig
s.StartTLS()
defer s.Close()
req := s.Client()
res, err := req.Get(fmt.Sprint(s.URL, "/test"))
if err != nil {
t.Fatal(err)
}
if res.StatusCode != 204 {
t.Errorf("expected status code 204, but got %d\nres: %v", res.StatusCode, res)
}
})
}
func TestNewTLSClientConfig(t *testing.T) {
rmFunc, _, _, ca := getPEMFiles(t)
defer rmFunc()
_, err := NewTLSClientConfig(ca)
if err != nil {
t.Errorf("Failed to create TLSConfig: %s", err)
}
}
func TestCanIssueRequest(t *testing.T) {
rmFunc, cert, key, ca := getPEMFiles(t)
defer rmFunc()
serverConfig, err := NewTLSConfig(cert, key, ca)
if err != nil {
t.Fatalf("Failed to create TLSConfig: %s", err)
}
// use our test grpc server with this tls
gs := grpc.NewServer(grpc.Creds(credentials.NewTLS(serverConfig)))
server_test.RegisterHelloServer(gs, server_test.HelloServerImpl{})
gsl, err := servertest.NewLocalListener()
if err != nil {
t.Fatal(err)
}
go gs.Serve(gsl)
defer gs.Stop()
clientConfig, err := NewTLSClientConfig(ca)
if err != nil {
t.Fatal(err)
}
conn, err := grpc.Dial(gsl.Addr().String(), grpc.WithTransportCredentials(credentials.NewTLS(clientConfig)))
defer conn.Close()
gc := server_test.NewHelloClient(conn)
res, err := gc.SayHello(context.Background(), &server_test.HelloRequest{Name: "test"})
if err != nil {
t.Fatal(err)
}
expected := "hello, test!"
if res.Greeting != expected {
t.Errorf("expected %q, but got %q", expected, res.Greeting)
}
}