forked from pieterlouw/caddy-grpc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
setup.go
89 lines (73 loc) · 2.01 KB
/
setup.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
package grpc
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"github.com/caddyserver/caddy"
"github.com/caddyserver/caddy/caddyhttp/httpserver"
)
func init() {
caddy.RegisterPlugin("grpc", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
// setup configures a new server middleware instance.
func setup(c *caddy.Controller) error {
for c.Next() {
var s server
if !c.Args(&s.backendAddr) { //loads next argument into backendAddr and fail if none specified
return c.ArgErr()
}
tlsConfig := &tls.Config{}
tlsConfig.MinVersion = tls.VersionTLS12
s.backendTLS = tlsConfig
s.backendIsInsecure = false
//check for more settings in Caddyfile
for c.NextBlock() {
switch c.Val() {
case "backend_is_insecure":
s.backendIsInsecure = true
case "backend_tls_noverify":
s.backendTLS = buildBackendTLSNoVerify()
case "backend_tls_ca_files":
t, err := buildBackendTLSFromCAFiles(c.RemainingArgs())
if err != nil {
return err
}
s.backendTLS = t
default:
return c.Errf("unknown property '%s'", c.Val())
}
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
s.next = next
return s
})
}
return nil
}
func buildBackendTLSNoVerify() *tls.Config {
tlsConfig := &tls.Config{}
tlsConfig.MinVersion = tls.VersionTLS12
tlsConfig.InsecureSkipVerify = true
return tlsConfig
}
func buildBackendTLSFromCAFiles(certs []string) (*tls.Config, error) {
tlsConfig := &tls.Config{}
tlsConfig.MinVersion = tls.VersionTLS12
if len(certs) > 0 {
tlsConfig.ClientCAs = x509.NewCertPool()
for _, path := range certs {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed reading backend CA file %v: %v", path, err)
}
if ok := tlsConfig.ClientCAs.AppendCertsFromPEM(data); !ok {
return nil, fmt.Errorf("failed processing backend CA file %v", path)
}
}
}
return tlsConfig, nil
}