forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpcserver.go
338 lines (316 loc) · 9.04 KB
/
grpcserver.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
Copyright 2018-2019 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package auth
import (
"context"
"io"
"net/http"
"strings"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth/proto"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/utils"
"github.com/golang/protobuf/ptypes/empty"
"github.com/gravitational/trace"
"github.com/gravitational/trace/trail"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/peer"
)
// GRPCServer is GPRC Auth Server API
type GRPCServer struct {
*logrus.Entry
APIConfig
// httpHandler is a server serving HTTP API
httpHandler http.Handler
// grpcHandler is golang GRPC handler
grpcHandler *grpc.Server
}
// SendKeepAlives allows node to send a stream of keep alive requests
func (g *GRPCServer) SendKeepAlives(stream proto.AuthService_SendKeepAlivesServer) error {
defer stream.SendAndClose(&empty.Empty{})
auth, err := g.authenticate(stream.Context())
if err != nil {
return trail.ToGRPC(err)
}
g.Debugf("Got heartbeat connection from %v.", auth.User.GetName())
for {
keepAlive, err := stream.Recv()
if err == io.EOF {
g.Debugf("Connection closed.")
return nil
}
if err != nil {
g.Debugf("Failed to receive heartbeat: %v", err)
return trail.ToGRPC(err)
}
err = auth.KeepAliveNode(stream.Context(), *keepAlive)
if err != nil {
return trail.ToGRPC(err)
}
}
}
// WatchEvents returns a new stream of cluster events
func (g *GRPCServer) WatchEvents(watch *proto.Watch, stream proto.AuthService_WatchEventsServer) error {
auth, err := g.authenticate(stream.Context())
if err != nil {
return trail.ToGRPC(err)
}
servicesWatch := services.Watch{
Name: auth.User.GetName(),
}
for _, kind := range watch.Kinds {
servicesWatch.Kinds = append(servicesWatch.Kinds, services.WatchKind{
Name: kind.Name,
Kind: kind.Kind,
LoadSecrets: kind.LoadSecrets,
})
}
watcher, err := auth.NewWatcher(stream.Context(), servicesWatch)
if err != nil {
return trail.ToGRPC(err)
}
defer watcher.Close()
for {
select {
case <-stream.Context().Done():
return nil
case <-watcher.Done():
return trail.ToGRPC(watcher.Error())
case event := <-watcher.Events():
out, err := eventToGRPC(event)
if err != nil {
return trail.ToGRPC(err)
}
if err := stream.Send(out); err != nil {
return trail.ToGRPC(err)
}
}
}
}
// UpsertNode upserts node
func (g *GRPCServer) UpsertNode(ctx context.Context, server *services.ServerV2) (*services.KeepAlive, error) {
auth, err := g.authenticate(ctx)
if err != nil {
return nil, trail.ToGRPC(err)
}
// Extract peer (remote host) from context and if the server sent 0.0.0.0 as
// its address (meaning it did not set an advertise address) update it with
// the address of the peer.
p, ok := peer.FromContext(ctx)
if !ok {
return nil, trail.ToGRPC(trace.BadParameter("unable to find peer"))
}
server.SetAddr(utils.ReplaceLocalhost(server.GetAddr(), p.Addr.String()))
keepAlive, err := auth.UpsertNode(server)
if err != nil {
return nil, trail.ToGRPC(err)
}
return keepAlive, nil
}
type grpcContext struct {
*AuthContext
*AuthWithRoles
}
// authenticate extracts authentication context and returns initialized auth server
func (g *GRPCServer) authenticate(ctx context.Context) (*grpcContext, error) {
// HTTPS server expects auth context to be set by the auth middleware
authContext, err := g.Authorizer.Authorize(ctx)
if err != nil {
// propagate connection problem error so we can differentiate
// between connection failed and access denied
if trace.IsConnectionProblem(err) {
return nil, trace.ConnectionProblem(err, "[10] failed to connect to the database")
} else if trace.IsAccessDenied(err) {
// don't print stack trace, just log the warning
log.Warn(err)
} else {
log.Warn(trace.DebugReport(err))
}
return nil, trace.AccessDenied("[10] access denied")
}
return &grpcContext{
AuthContext: authContext,
AuthWithRoles: &AuthWithRoles{
authServer: g.AuthServer,
user: authContext.User,
checker: authContext.Checker,
sessions: g.SessionService,
alog: g.AuthServer.IAuditLog,
},
}, nil
}
// NewGRPCServer returns a new instance of GRPC server
func NewGRPCServer(cfg APIConfig) http.Handler {
authServer := &GRPCServer{
APIConfig: cfg,
Entry: logrus.WithFields(logrus.Fields{
trace.Component: teleport.Component(teleport.ComponentAuth, teleport.ComponentGRPC),
}),
httpHandler: NewAPIServer(&cfg),
grpcHandler: grpc.NewServer(),
}
proto.RegisterAuthServiceServer(authServer.grpcHandler, authServer)
return authServer
}
// ServeHTTP dispatches requests based on the request type
func (g *GRPCServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// magic combo match signifying GRPC request
// https://grpc.io/blog/coreos
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
g.grpcHandler.ServeHTTP(w, r)
} else {
g.httpHandler.ServeHTTP(w, r)
}
}
func eventToGRPC(in services.Event) (*proto.Event, error) {
eventType, err := eventTypeToGRPC(in.Type)
if err != nil {
return nil, trace.Wrap(err)
}
out := proto.Event{
Type: eventType,
}
if in.Type == backend.OpInit {
return &out, nil
}
switch r := in.Resource.(type) {
case *services.ResourceHeader:
out.Resource = &proto.Event_ResourceHeader{
ResourceHeader: r,
}
case *services.CertAuthorityV2:
out.Resource = &proto.Event_CertAuthority{
CertAuthority: r,
}
case *services.StaticTokensV2:
out.Resource = &proto.Event_StaticTokens{
StaticTokens: r,
}
case *services.ProvisionTokenV2:
out.Resource = &proto.Event_ProvisionToken{
ProvisionToken: r,
}
case *services.ClusterNameV2:
out.Resource = &proto.Event_ClusterName{
ClusterName: r,
}
case *services.ClusterConfigV3:
out.Resource = &proto.Event_ClusterConfig{
ClusterConfig: r,
}
case *services.UserV2:
out.Resource = &proto.Event_User{
User: r,
}
case *services.RoleV3:
out.Resource = &proto.Event_Role{
Role: r,
}
case *services.Namespace:
out.Resource = &proto.Event_Namespace{
Namespace: r,
}
case *services.ServerV2:
out.Resource = &proto.Event_Server{
Server: r,
}
case *services.ReverseTunnelV2:
out.Resource = &proto.Event_ReverseTunnel{
ReverseTunnel: r,
}
case *services.TunnelConnectionV2:
out.Resource = &proto.Event_TunnelConnection{
TunnelConnection: r,
}
default:
return nil, trace.BadParameter("resource type %T is not supported", in.Resource)
}
return &out, nil
}
func eventTypeToGRPC(in backend.OpType) (proto.Operation, error) {
switch in {
case backend.OpInit:
return proto.Operation_INIT, nil
case backend.OpPut:
return proto.Operation_PUT, nil
case backend.OpDelete:
return proto.Operation_DELETE, nil
default:
return -1, trace.BadParameter("event type %v is not supported", in)
}
}
func eventFromGRPC(in proto.Event) (*services.Event, error) {
eventType, err := eventTypeFromGRPC(in.Type)
if err != nil {
return nil, trace.Wrap(err)
}
out := services.Event{
Type: eventType,
}
if eventType == backend.OpInit {
return &out, nil
}
if r := in.GetResourceHeader(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetCertAuthority(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetStaticTokens(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetProvisionToken(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetClusterName(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetClusterConfig(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetUser(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetRole(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetNamespace(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetServer(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetReverseTunnel(); r != nil {
out.Resource = r
return &out, nil
} else if r := in.GetTunnelConnection(); r != nil {
out.Resource = r
return &out, nil
} else {
return nil, trace.BadParameter("received unsupported resource %T", in.Resource)
}
}
func eventTypeFromGRPC(in proto.Operation) (backend.OpType, error) {
switch in {
case proto.Operation_INIT:
return backend.OpInit, nil
case proto.Operation_PUT:
return backend.OpPut, nil
case proto.Operation_DELETE:
return backend.OpDelete, nil
default:
return -1, trace.BadParameter("unsupported operation type: %v", in)
}
}