-
Notifications
You must be signed in to change notification settings - Fork 40
/
dialer.go
613 lines (547 loc) · 18.9 KB
/
dialer.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
package rpc
import (
"context"
"crypto/tls"
"encoding/hex"
"fmt"
"hash/fnv"
"strings"
"sync"
"github.com/edaniels/golog"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
"github.com/pion/webrtc/v3"
"github.com/pkg/errors"
"go.uber.org/multierr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"go.viam.com/utils"
rpcpb "go.viam.com/utils/proto/rpc/v1"
)
// create a new TLS config with the default options for RPC.
func newDefaultTLSConfig() *tls.Config {
return &tls.Config{MinVersion: tls.VersionTLS12}
}
// A Dialer is responsible for making connections to gRPC endpoints.
type Dialer interface {
// DialDirect makes a connection to the given target over standard gRPC with the supplied options.
DialDirect(
ctx context.Context,
target string,
keyExtra string,
onClose func() error,
opts ...grpc.DialOption,
) (conn ClientConn, cached bool, err error)
// DialFunc makes a connection to the given target for the given proto using the given dial function.
DialFunc(
proto string,
target string,
keyExtra string,
dialNew func() (ClientConn, func() error, error),
) (conn ClientConn, cached bool, err error)
// Close ensures all connections made are cleanly closed.
Close() error
}
// A ClientConn is a wrapper around the gRPC client connection interface but ensures
// there is a way to close the connection.
type ClientConn interface {
grpc.ClientConnInterface
// PeerConn returns the backing PeerConnection object, or nil if the underlying transport is not
// a PeerConnection.
PeerConn() *webrtc.PeerConnection
Close() error
}
// A ClientConnAuthenticator supports instructing a connection to authenticate now.
type ClientConnAuthenticator interface {
ClientConn
Authenticate(ctx context.Context) (string, error)
}
// A GrpcOverHTTPClientConn is grpc connection that is not backed by a `webrtc.PeerConnection`.
type GrpcOverHTTPClientConn struct {
*grpc.ClientConn
}
// PeerConn returns nil as this is a native gRPC connection.
func (cc GrpcOverHTTPClientConn) PeerConn() *webrtc.PeerConnection {
return nil
}
type cachedDialer struct {
mu sync.Mutex // Note(erd): not suitable for highly concurrent usage
conns map[string]*refCountedConnWrapper
}
// NewCachedDialer returns a Dialer that returns the same connection if it
// already has been established at a particular target (regardless of the
// options used).
func NewCachedDialer() Dialer {
return &cachedDialer{conns: map[string]*refCountedConnWrapper{}}
}
func (cd *cachedDialer) DialDirect(
ctx context.Context,
target string,
keyExtra string,
onClose func() error,
opts ...grpc.DialOption,
) (ClientConn, bool, error) {
return cd.DialFunc("grpc", target, keyExtra, func() (ClientConn, func() error, error) {
conn, err := grpc.DialContext(ctx, target, opts...)
if err != nil {
return nil, nil, err
}
return GrpcOverHTTPClientConn{conn}, onClose, nil
})
}
func (cd *cachedDialer) DialFunc(
proto string,
target string,
keyExtra string,
dialNew func() (ClientConn, func() error, error),
) (ClientConn, bool, error) {
key := fmt.Sprintf("%s:%s:%s", proto, target, keyExtra)
cd.mu.Lock()
c, ok := cd.conns[key]
cd.mu.Unlock()
if ok {
return c.Ref(), true, nil
}
// assume any difference in opts does not matter
conn, onClose, err := dialNew()
if err != nil {
return nil, false, err
}
conn = wrapClientConnWithCloseFunc(conn, onClose)
refConn := newRefCountedConnWrapper(proto, conn, func() {
cd.mu.Lock()
delete(cd.conns, key)
cd.mu.Unlock()
})
cd.mu.Lock()
defer cd.mu.Unlock()
// someone else might have already connected
c, ok = cd.conns[key]
if ok {
if err := conn.Close(); err != nil {
return nil, false, err
}
return c.Ref(), true, nil
}
cd.conns[key] = refConn
return refConn.Ref(), false, nil
}
func (cd *cachedDialer) Close() error {
cd.mu.Lock()
// need a copy of cd.conns as we can't hold the lock, since .Close() fires the onUnref() set (above) in DialFunc()
// that uses the same lock and directly modifies cd.conns when the dialer is reused at different layers (e.g. auth and multi)
var conns []*refCountedConnWrapper
for _, c := range cd.conns {
conns = append(conns, c)
}
cd.mu.Unlock()
var err error
for _, c := range conns {
if closeErr := c.actual.Close(); closeErr != nil && status.Convert(closeErr).Code() != codes.Canceled {
err = multierr.Combine(err, closeErr)
}
}
return err
}
// newRefCountedConnWrapper wraps the given connection to be able to be reference counted.
func newRefCountedConnWrapper(proto string, conn ClientConn, onUnref func()) *refCountedConnWrapper {
return &refCountedConnWrapper{proto, utils.NewRefCountedValue(conn), conn, onUnref}
}
// refCountedConnWrapper wraps a ClientConn to be reference counted.
type refCountedConnWrapper struct {
proto string
ref utils.RefCountedValue
actual ClientConn
onUnref func()
}
// Ref returns a new reference to the underlying ClientConn.
func (w *refCountedConnWrapper) Ref() ClientConn {
return &reffedConn{ClientConn: w.ref.Ref().(ClientConn), proto: w.proto, deref: w.ref.Deref, onUnref: w.onUnref}
}
// A reffedConn reference counts a ClieentConn and closes it on the last dereference.
type reffedConn struct {
ClientConn
proto string
derefOnce sync.Once
deref func() bool
onUnref func()
}
// Close will deref the reference and if it is the last to do so, will close
// the underlying connection.
func (rc *reffedConn) Close() error {
var err error
rc.derefOnce.Do(func() {
if unref := rc.deref(); unref {
if rc.onUnref != nil {
defer rc.onUnref()
}
if utils.Debug {
golog.Global().Debugw("close referenced conn", "proto", rc.proto)
}
if closeErr := rc.ClientConn.Close(); closeErr != nil && status.Convert(closeErr).Code() != codes.Canceled {
err = closeErr
}
}
})
return err
}
// ErrInsecureWithCredentials is sent when a dial attempt is made to an address where either the insecure
// option or insecure downgrade with credentials options are not set.
var ErrInsecureWithCredentials = errors.New("requested address is insecure and will not send credentials")
// DialDirectGRPC dials a gRPC server directly.
func DialDirectGRPC(ctx context.Context, address string, logger golog.Logger, opts ...DialOption) (ClientConn, error) {
var dOpts dialOptions
for _, opt := range opts {
opt.apply(&dOpts)
}
dOpts.webrtcOpts.Disable = true
dOpts.mdnsOptions.Disable = true
if logger == nil {
logger = zap.NewNop().Sugar()
}
return dialInner(ctx, address, logger, dOpts)
}
// dialDirectGRPC dials a gRPC server directly.
func dialDirectGRPC(ctx context.Context, address string, dOpts dialOptions, logger golog.Logger) (ClientConn, bool, error) {
dialOpts := []grpc.DialOption{
grpc.WithBlock(),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(MaxMessageSize)),
}
if dOpts.insecure {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else {
tlsConfig := dOpts.tlsConfig
if tlsConfig == nil {
tlsConfig = newDefaultTLSConfig()
}
var downgrade bool
if dOpts.allowInsecureDowngrade || dOpts.allowInsecureWithCredsDowngrade {
var dialer tls.Dialer
dialer.Config = tlsConfig
conn, err := dialer.DialContext(ctx, "tcp", address)
if err == nil {
// will use TLS
utils.UncheckedError(conn.Close())
} else if strings.Contains(err.Error(), "tls: first record does not look like a TLS handshake") {
// unfortunately there's no explicit error value for this, so we do a string check
hasLocalCreds := dOpts.creds.Type != "" && dOpts.externalAuthAddr == ""
if dOpts.creds.Type == "" || !hasLocalCreds || dOpts.allowInsecureWithCredsDowngrade {
logger.Warnw("downgrading from TLS to plaintext", "address", address, "with_credentials", hasLocalCreds)
downgrade = true
} else if hasLocalCreds {
return nil, false, ErrInsecureWithCredentials
}
}
}
if downgrade {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
}
}
if dOpts.statsHandler != nil {
dialOpts = append(dialOpts, grpc.WithStatsHandler(dOpts.statsHandler))
}
grpcLogger := logger.Desugar()
if !(dOpts.debug || utils.Debug) {
grpcLogger = grpcLogger.WithOptions(zap.IncreaseLevel(zap.LevelEnablerFunc(zapcore.ErrorLevel.Enabled)))
}
var unaryInterceptors []grpc.UnaryClientInterceptor
unaryInterceptors = append(unaryInterceptors, grpc_zap.UnaryClientInterceptor(grpcLogger))
unaryInterceptors = append(unaryInterceptors, UnaryClientTracingInterceptor())
if dOpts.unaryInterceptor != nil {
unaryInterceptors = append(unaryInterceptors, dOpts.unaryInterceptor)
}
var streamInterceptors []grpc.StreamClientInterceptor
streamInterceptors = append(streamInterceptors, grpc_zap.StreamClientInterceptor(grpcLogger))
streamInterceptors = append(streamInterceptors, StreamClientTracingInterceptor())
if dOpts.streamInterceptor != nil {
streamInterceptors = append(streamInterceptors, dOpts.streamInterceptor)
}
var connPtr *ClientConn
var closeCredsFunc func() error
var rpcCreds *perRPCJWTCredentials
if dOpts.authMaterial != "" {
dialOpts = append(dialOpts, grpc.WithPerRPCCredentials(&staticPerRPCJWTCredentials{dOpts.authMaterial}))
} else if dOpts.creds.Type != "" || dOpts.externalAuthMaterial != "" {
rpcCreds = &perRPCJWTCredentials{
entity: dOpts.authEntity,
creds: dOpts.creds,
debug: dOpts.debug,
logger: logger,
// Note: don't set dialOptsCopy.authMaterial below as perRPCJWTCredentials will know to use
// its externalAccessToken to authenticateTo. This will result in both a connection level authorization
// added as well as an authorization header added from perRPCJWTCredentials, resulting in a failure.
externalAuthMaterial: dOpts.externalAuthMaterial,
}
if dOpts.debug && dOpts.externalAuthAddr != "" && dOpts.externalAuthToEntity != "" {
logger.Debugw("will eventually authenticate as entity", "entity", dOpts.authEntity)
}
if dOpts.externalAuthAddr != "" {
externalConn, err := dialExternalAuthEntity(ctx, logger, dOpts)
if err != nil {
return nil, false, err
}
closeCredsFunc = externalConn.Close
rpcCreds.conn = externalConn
rpcCreds.externalAuthToEntity = dOpts.externalAuthToEntity
} else {
connPtr = &rpcCreds.conn
}
dialOpts = append(dialOpts, grpc.WithPerRPCCredentials(rpcCreds))
unaryInterceptors = append(unaryInterceptors, UnaryClientInvalidAuthInterceptor(rpcCreds))
// InvalidAuthInterceptor will not work for streaming calls; we can only
// intercept the creation of a stream, and the ensuring of authentication
// server-side happens per RPC request (per usage of the stream).
}
unaryInterceptor := grpc_middleware.ChainUnaryClient(unaryInterceptors...)
dialOpts = append(dialOpts, grpc.WithUnaryInterceptor(unaryInterceptor))
streamInterceptor := grpc_middleware.ChainStreamClient(streamInterceptors...)
dialOpts = append(dialOpts, grpc.WithStreamInterceptor(streamInterceptor))
var conn ClientConn
var cached bool
var err error
if ctxDialer := contextDialer(ctx); ctxDialer != nil {
conn, cached, err = ctxDialer.DialDirect(ctx, address, dOpts.cacheKey(), closeCredsFunc, dialOpts...)
} else {
var grpcConn *grpc.ClientConn
grpcConn, err = grpc.DialContext(ctx, address, dialOpts...)
if err == nil {
conn = GrpcOverHTTPClientConn{grpcConn}
}
if err == nil && closeCredsFunc != nil {
conn = wrapClientConnWithCloseFunc(conn, closeCredsFunc)
}
}
if err != nil {
if closeCredsFunc != nil {
err = multierr.Combine(err, closeCredsFunc())
}
return nil, false, err
}
if connPtr != nil {
*connPtr = conn
}
if rpcCreds != nil {
conn = clientConnRPCAuthenticator{conn, rpcCreds}
}
return conn, cached, err
}
func dialExternalAuthEntity(ctx context.Context, logger golog.Logger, dOpts dialOptions) (ClientConn, error) {
if dOpts.externalAuthToEntity == "" {
return nil, errors.New("external auth address set but no authenticate to option set")
}
if dOpts.debug {
logger.Debugw("will eventually authenticate externally to entity", "entity", dOpts.externalAuthToEntity)
logger.Debugw("dialing direct for external auth", "address", dOpts.externalAuthAddr)
}
address := dOpts.externalAuthAddr
dOpts.externalAuthAddr = ""
dOpts.insecure = dOpts.externalAuthInsecure
dOpts.externalAuthMaterial = ""
dOpts.creds = Credentials{}
dOpts.authEntity = ""
// reset the tls config that is used for the external Auth Service.
dOpts.tlsConfig = newDefaultTLSConfig()
conn, cached, err := dialDirectGRPC(ctx, address, dOpts, logger)
if dOpts.debug {
logger.Debugw("connected directly for external auth", "address", address, "cached", cached)
}
return conn, err
}
// cacheKey hashes options to only cache when authentication material
// is the same between dials. That means any time a new way that differs
// authentication based on options is introduced, this function should
// also be updated.
func (dOpts dialOptions) cacheKey() string {
hasher := fnv.New128a()
if dOpts.authEntity != "" {
hasher.Write([]byte(dOpts.authEntity))
}
if dOpts.creds.Type != "" {
hasher.Write([]byte(dOpts.creds.Type))
}
if dOpts.creds.Payload != "" {
hasher.Write([]byte(dOpts.creds.Payload))
}
if dOpts.externalAuthAddr != "" {
hasher.Write([]byte(dOpts.externalAuthAddr))
}
if dOpts.externalAuthToEntity != "" {
hasher.Write([]byte(dOpts.externalAuthToEntity))
}
if dOpts.externalAuthMaterial != "" {
hasher.Write([]byte(dOpts.externalAuthMaterial))
}
if dOpts.webrtcOpts.SignalingServerAddress != "" {
hasher.Write([]byte(dOpts.webrtcOpts.SignalingServerAddress))
}
if dOpts.webrtcOpts.SignalingExternalAuthAddress != "" {
hasher.Write([]byte(dOpts.webrtcOpts.SignalingExternalAuthAddress))
}
if dOpts.webrtcOpts.SignalingExternalAuthToEntity != "" {
hasher.Write([]byte(dOpts.webrtcOpts.SignalingExternalAuthToEntity))
}
if dOpts.webrtcOpts.SignalingExternalAuthAuthMaterial != "" {
hasher.Write([]byte(dOpts.webrtcOpts.SignalingExternalAuthAuthMaterial))
}
if dOpts.webrtcOpts.SignalingCreds.Type != "" {
hasher.Write([]byte(dOpts.webrtcOpts.SignalingCreds.Type))
}
if dOpts.webrtcOpts.SignalingCreds.Payload != "" {
hasher.Write([]byte(dOpts.webrtcOpts.SignalingCreds.Payload))
}
return hex.EncodeToString(hasher.Sum(nil))
}
func wrapClientConnWithCloseFunc(conn ClientConn, closeFunc func() error) ClientConn {
return &clientConnWithCloseFunc{ClientConn: conn, closeFunc: closeFunc}
}
type clientConnWithCloseFunc struct {
ClientConn
closeFunc func() error
}
func (cc *clientConnWithCloseFunc) Close() (err error) {
defer func() {
if cc.closeFunc == nil {
return
}
err = multierr.Combine(err, cc.closeFunc())
}()
return cc.ClientConn.Close()
}
// dialFunc dials an address for a particular protocol and dial function.
func dialFunc(
ctx context.Context,
proto string,
target string,
keyExtra string,
f func() (ClientConn, error),
) (ClientConn, bool, error) {
if ctxDialer := contextDialer(ctx); ctxDialer != nil {
return ctxDialer.DialFunc(proto, target, keyExtra, func() (ClientConn, func() error, error) {
conn, err := f()
return conn, nil, err
})
}
conn, err := f()
return conn, false, err
}
type clientConnRPCAuthenticator struct {
ClientConn
rpcCreds *perRPCJWTCredentials
}
func (cc clientConnRPCAuthenticator) Authenticate(ctx context.Context) (string, error) {
return cc.rpcCreds.authenticate(ctx)
}
type staticPerRPCJWTCredentials struct {
authMaterial string
}
func (creds *staticPerRPCJWTCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
for _, uriVal := range uri {
if strings.HasSuffix(uriVal, "/proto.rpc.v1.AuthService") {
//nolint:nilnil
return nil, nil
}
}
return map[string]string{"Authorization": "Bearer " + creds.authMaterial}, nil
}
func (creds *staticPerRPCJWTCredentials) RequireTransportSecurity() bool {
return false
}
type perRPCJWTCredentials struct {
mu sync.RWMutex
conn ClientConn
entity string
externalAuthToEntity string
creds Credentials
accessToken string
// The static external auth material used against the AuthenticateTo request to obtain final accessToken
externalAuthMaterial string
debug bool
logger golog.Logger
}
// TODO(GOUT-10): handle expiration.
func (creds *perRPCJWTCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
for _, uriVal := range uri {
if strings.HasSuffix(uriVal, "/proto.rpc.v1.AuthService") {
//nolint:nilnil
return nil, nil
}
}
accessToken, err := creds.authenticate(ctx)
if err != nil {
return nil, err
}
return map[string]string{"Authorization": "Bearer " + accessToken}, nil
}
func (creds *perRPCJWTCredentials) authenticate(ctx context.Context) (string, error) {
creds.mu.RLock()
accessToken := creds.accessToken
creds.mu.RUnlock()
if accessToken == "" {
creds.mu.Lock()
defer creds.mu.Unlock()
accessToken = creds.accessToken
if accessToken == "" {
// skip authenticate call when a static access token for the external auth is used.
if creds.externalAuthMaterial == "" {
if creds.debug {
creds.logger.Debugw("authenticating as entity", "entity", creds.entity)
}
authClient := rpcpb.NewAuthServiceClient(creds.conn)
// Check external auth creds...
resp, err := authClient.Authenticate(ctx, &rpcpb.AuthenticateRequest{
Entity: creds.entity,
Credentials: &rpcpb.Credentials{
Type: string(creds.creds.Type),
Payload: creds.creds.Payload,
},
})
if err != nil {
return "", err
}
accessToken = resp.AccessToken
} else {
accessToken = creds.externalAuthMaterial
}
// now perform external auth
if creds.externalAuthToEntity == "" {
if creds.debug {
creds.logger.Debug("not external auth for an entity; done")
}
creds.accessToken = accessToken
} else {
if creds.debug {
creds.logger.Debugw("authenticating to external entity", "entity", creds.externalAuthToEntity)
}
// now perform external auth
md := make(metadata.MD)
bearer := fmt.Sprintf("Bearer %s", accessToken)
md.Set("authorization", bearer)
externalCtx := metadata.NewOutgoingContext(ctx, md)
externalAuthClient := rpcpb.NewExternalAuthServiceClient(creds.conn)
externalResp, err := externalAuthClient.AuthenticateTo(externalCtx, &rpcpb.AuthenticateToRequest{
Entity: creds.externalAuthToEntity,
})
if err != nil {
return "", err
}
if creds.debug {
creds.logger.Debugw("external auth done", "auth_to", creds.externalAuthToEntity)
}
accessToken = externalResp.AccessToken
creds.accessToken = externalResp.AccessToken
}
}
}
return accessToken, nil
}
func (creds *perRPCJWTCredentials) RequireTransportSecurity() bool {
return false
}