-
Notifications
You must be signed in to change notification settings - Fork 165
/
grpc.go
226 lines (180 loc) · 5.58 KB
/
grpc.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package backends
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"google.golang.org/grpc/credentials/insecure"
"io/ioutil"
"strconv"
"time"
"github.com/golang/protobuf/ptypes/empty"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
gs "github.com/iegomez/mosquitto-go-auth/grpc"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// GRPC holds a client for the service and implements the Backend interface.
type GRPC struct {
client gs.AuthServiceClient
conn *grpc.ClientConn
disableSuperuser bool
dialOptions []grpc.DialOption
hostname string
timeout int
}
const defaultGRPCTimeoutMs = 500
// NewGRPC tries to connect to the gRPC service at the given host.
func NewGRPC(authOpts map[string]string, logLevel log.Level) (*GRPC, error) {
g := &GRPC{
timeout: defaultGRPCTimeoutMs,
}
if authOpts["grpc_host"] == "" || authOpts["grpc_port"] == "" {
return nil, errors.New("grpc must have a host and port")
}
if authOpts["grpc_disable_superuser"] == "true" {
g.disableSuperuser = true
}
if timeout, ok := authOpts["grpc_dial_timeout_ms"]; ok {
timeoutMs, err := strconv.Atoi(timeout)
if err != nil {
log.Warnf("invalid grpc dial timeout value: %s", err)
} else {
g.timeout = timeoutMs
}
}
caCert := authOpts["grpc_ca_cert"]
tlsCert := authOpts["grpc_tls_cert"]
tlsKey := authOpts["grpc_tls_key"]
addr := fmt.Sprintf("%s:%s", authOpts["grpc_host"], authOpts["grpc_port"])
withBlock := authOpts["grpc_fail_on_dial_error"] == "true"
options, err := setup(addr, caCert, tlsCert, tlsKey, withBlock)
if err != nil {
return nil, err
}
g.dialOptions = options
g.hostname = addr
err = g.initClient()
if err != nil {
return nil, err
}
return g, nil
}
// GetUser checks that the username exists and the given password hashes to the same password.
func (o *GRPC) GetUser(username, password, clientid string) (bool, error) {
req := gs.GetUserRequest{
Username: username,
Password: password,
Clientid: clientid,
}
resp, err := o.client.GetUser(context.Background(), &req)
if err != nil {
log.Errorf("grpc get user error: %s", err)
return false, err
}
return resp.Ok, nil
}
// GetSuperuser checks that the user is a superuser.
func (o *GRPC) GetSuperuser(username string) (bool, error) {
if o.disableSuperuser {
return false, nil
}
req := gs.GetSuperuserRequest{
Username: username,
}
resp, err := o.client.GetSuperuser(context.Background(), &req)
if err != nil {
log.Errorf("grpc get superuser error: %s", err)
return false, err
}
return resp.Ok, nil
}
// CheckAcl checks if the user has access to the given topic.
func (o *GRPC) CheckAcl(username, topic, clientid string, acc int32) (bool, error) {
req := gs.CheckAclRequest{
Username: username,
Topic: topic,
Clientid: clientid,
Acc: acc,
}
resp, err := o.client.CheckAcl(context.Background(), &req)
if err != nil {
log.Errorf("grpc check acl error: %s", err)
return false, err
}
return resp.Ok, nil
}
// GetName gets the gRPC backend's name.
func (o *GRPC) GetName() string {
resp, err := o.client.GetName(context.Background(), &empty.Empty{})
if err != nil {
return "grpc get name error"
}
return resp.Name
}
// Halt signals the gRPC backend that mosquitto is halting.
func (o *GRPC) Halt() {
_, err := o.client.Halt(context.Background(), &empty.Empty{})
if err != nil {
log.Errorf("grpc halt: %s", err)
}
if o.conn != nil {
o.conn.Close()
}
}
func setup(hostname string, caCert string, tlsCert string, tlsKey string, withBlock bool) ([]grpc.DialOption, error) {
logrusEntry := log.NewEntry(log.StandardLogger())
logrusOpts := []grpc_logrus.Option{
grpc_logrus.WithLevels(grpc_logrus.DefaultCodeToLevel),
}
nsOpts := []grpc.DialOption{
grpc.WithUnaryInterceptor(
grpc_logrus.UnaryClientInterceptor(logrusEntry, logrusOpts...),
),
}
if withBlock {
nsOpts = append(nsOpts, grpc.WithBlock())
}
if len(caCert) == 0 {
nsOpts = append(nsOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
log.WithField("server", hostname).Warning("creating insecure grpc client")
} else {
log.WithField("server", hostname).Info("creating grpc client")
caCertBytes, err := ioutil.ReadFile(caCert)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("could not load grpc ca certificate (grpc_ca_cert) from file (%s)", caCert))
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCertBytes) {
return nil, errors.New("append ca cert to pool error. Maybe the ca file (grpc_ca_cert) does not contain a valid x509 certificate")
}
tlsConfig := &tls.Config{
RootCAs: caCertPool,
}
if len(tlsCert) != 0 && len(tlsKey) != 0 {
cert, err := tls.LoadX509KeyPair(tlsCert, tlsKey)
if err != nil {
return nil, errors.Wrap(err, "load x509 keypair error")
}
certificates := []tls.Certificate{cert}
tlsConfig.Certificates = certificates
} else if len(tlsCert) != 0 || len(tlsKey) != 0 {
log.Warn("gRPC backend warning: mutual TLS was disabled due to missing client certificate (grpc_tls_cert) or client key (grpc_tls_key)")
}
nsOpts = append(nsOpts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
}
return nsOpts, nil
}
func (g *GRPC) initClient() error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(g.timeout)*time.Millisecond)
defer cancel()
gsClient, err := grpc.DialContext(ctx, g.hostname, g.dialOptions...)
if err != nil {
return err
}
g.conn = gsClient
g.client = gs.NewAuthServiceClient(gsClient)
return nil
}