-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
client.go
2752 lines (2446 loc) · 93.9 KB
/
client.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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2020-2022 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 client
import (
"compress/gzip"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/gravitational/teleport/api/breaker"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/constants"
"github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/metadata"
"github.com/gravitational/teleport/api/observability/tracing"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/api/utils"
"github.com/golang/protobuf/ptypes/empty"
"github.com/gravitational/trace"
"github.com/gravitational/trace/trail"
"github.com/jonboulle/clockwork"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"golang.org/x/crypto/ssh"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials"
ggzip "google.golang.org/grpc/encoding/gzip"
"google.golang.org/grpc/keepalive"
)
func init() {
// gzip is used for gRPC auditStream compression. SetLevel changes the
// compression level, must be called in initialization, and is not thread safe.
if err := ggzip.SetLevel(gzip.BestSpeed); err != nil {
panic(err)
}
}
// Client is a gRPC Client that connects to a Teleport Auth server either
// locally or over ssh through a Teleport web proxy or tunnel proxy.
//
// This client can be used to cover a variety of Teleport use cases,
// such as programmatically handling access requests, integrating
// with external tools, or dynamically configuring Teleport.
type Client struct {
// c contains configuration values for the client.
c Config
// tlsConfig is the *tls.Config for a successfully connected client.
tlsConfig *tls.Config
// dialer is the ContextDialer for a successfully connected client.
dialer ContextDialer
// conn is a grpc connection to the auth server.
conn *grpc.ClientConn
// grpc is the gRPC client specification for the auth server.
grpc proto.AuthServiceClient
// JoinServiceClient is a client for the JoinService, which runs on both the
// auth and proxy.
*JoinServiceClient
// closedFlag is set to indicate that the connection is closed.
// It's a pointer to allow the Client struct to be copied.
closedFlag *int32
// callOpts configure calls made by this client.
callOpts []grpc.CallOption
}
// New creates a new Client with an open connection to a Teleport server.
//
// New will try to open a connection with all combinations of addresses and credentials.
// The first successful connection to a server will be used, or an aggregated error will
// be returned if all combinations fail.
//
// cfg.Credentials must be non-empty. One of cfg.Addrs and cfg.Dialer must be non-empty,
// unless LoadProfile is used to fetch Credentials and load a web proxy dialer.
//
// See the example below for usage.
func New(ctx context.Context, cfg Config) (clt *Client, err error) {
if err = cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
// If cfg.DialInBackground is true, only a single connection is attempted.
// This option is primarily meant for internal use where the client has
// direct access to server values that guarantee a successful connection.
if cfg.DialInBackground {
return connectInBackground(ctx, cfg)
}
return connect(ctx, cfg)
}
// NewTracingClient creates a new tracing.Client that will forward spans to the
// connected Teleport server. See New for details on how the connection it
// established.
func NewTracingClient(ctx context.Context, cfg Config) (*tracing.Client, error) {
clt, err := New(ctx, cfg)
if err != nil {
return nil, trace.Wrap(err)
}
return tracing.NewClient(clt.GetConnection()), nil
}
// newClient constructs a new client.
func newClient(cfg Config, dialer ContextDialer, tlsConfig *tls.Config) *Client {
return &Client{
c: cfg,
dialer: dialer,
tlsConfig: ConfigureALPN(tlsConfig, cfg.ALPNSNIAuthDialClusterName),
closedFlag: new(int32),
}
}
// connectInBackground connects the client to the server in the background.
// The client will use the first credentials and the given dialer. If
// no dialer is given, the first address will be used. This address must
// be an auth server address.
func connectInBackground(ctx context.Context, cfg Config) (*Client, error) {
tlsConfig, err := cfg.Credentials[0].TLSConfig()
if err != nil {
return nil, trace.Wrap(err)
}
if cfg.Dialer != nil {
return dialerConnect(ctx, connectParams{
cfg: cfg,
tlsConfig: tlsConfig,
dialer: cfg.Dialer,
})
} else if len(cfg.Addrs) != 0 {
return authConnect(ctx, connectParams{
cfg: cfg,
tlsConfig: tlsConfig,
addr: cfg.Addrs[0],
})
}
return nil, trace.BadParameter("must provide Dialer or Addrs in config")
}
// connect connects the client to the server using the Credentials and
// Dialer/Addresses provided in the client's config. Multiple goroutines are started
// to make dial attempts with different combinations of dialers and credentials. The
// first client to successfully connect is used to populate the client's connection
// attributes. If none successfully connect, an aggregated error is returned.
func connect(ctx context.Context, cfg Config) (*Client, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
// sendError is used to send errors to errChan with context.
errChan := make(chan error)
sendError := func(err error) {
errChan <- trace.Wrap(err)
}
// syncConnect is used to concurrently create multiple clients
// with the different combination of connection parameters.
// The first successful client to be sent to cltChan will be returned.
cltChan := make(chan *Client)
syncConnect := func(ctx context.Context, connect connectFunc, params connectParams) {
wg.Add(1)
go func() {
defer wg.Done()
clt, err := connect(ctx, params)
if err != nil {
sendError(trace.Wrap(err))
return
}
select {
case cltChan <- clt:
case <-ctx.Done():
clt.Close()
}
}()
}
wg.Add(1)
go func() {
defer wg.Done()
// Connect with provided credentials.
for _, creds := range cfg.Credentials {
tlsConfig, err := creds.TLSConfig()
if err != nil {
sendError(trace.Wrap(err))
continue
}
sshConfig, err := creds.SSHClientConfig()
if err != nil && !trace.IsNotImplemented(err) {
sendError(trace.Wrap(err))
continue
}
// Connect with dialer provided in config.
if cfg.Dialer != nil {
syncConnect(ctx, dialerConnect, connectParams{
cfg: cfg,
tlsConfig: tlsConfig,
})
}
// Connect with dialer provided in creds.
if dialer, err := creds.Dialer(cfg); err != nil {
if !trace.IsNotImplemented(err) {
sendError(trace.Wrap(err, "failed to retrieve dialer from creds of type %T", creds))
}
} else {
syncConnect(ctx, dialerConnect, connectParams{
cfg: cfg,
tlsConfig: tlsConfig,
dialer: dialer,
})
}
// Attempt to connect to each address as Auth, Proxy, Tunnel and TLS Routing.
for _, addr := range cfg.Addrs {
syncConnect(ctx, authConnect, connectParams{
cfg: cfg,
tlsConfig: tlsConfig,
addr: addr,
})
if sshConfig != nil {
for _, cf := range []connectFunc{proxyConnect, tunnelConnect, tlsRoutingConnect} {
syncConnect(ctx, cf, connectParams{
cfg: cfg,
tlsConfig: tlsConfig,
sshConfig: sshConfig,
addr: addr,
})
}
}
}
}
}()
// Start goroutine to wait for wait group.
go func() {
wg.Wait()
// Close errChan to return errors.
close(errChan)
}()
var errs []error
for errChan != nil {
select {
// Use the first client to successfully connect in syncConnect.
case clt := <-cltChan:
return clt, nil
case err, ok := <-errChan:
if ok {
// Add a new line to make errs human readable.
errs = append(errs, trace.Wrap(err, ""))
continue
}
errChan = nil
}
}
// errChan is closed, return errors.
if len(errs) == 0 {
if len(cfg.Addrs) == 0 && cfg.Dialer == nil {
// Some credentials don't require these fields. If no errors propagate, then they need to provide these fields.
return nil, trace.BadParameter("no connection methods found, try providing Dialer or Addrs in config")
}
// This case should never be reached with config validation and above case.
return nil, trace.Errorf("no connection methods found")
}
if ctx.Err() != nil {
errs = append(errs, trace.Wrap(ctx.Err()))
}
return nil, trace.Wrap(trace.NewAggregate(errs...), "all connection methods failed")
}
type (
connectFunc func(ctx context.Context, params connectParams) (*Client, error)
connectParams struct {
cfg Config
addr string
tlsConfig *tls.Config
dialer ContextDialer
sshConfig *ssh.ClientConfig
}
)
// authConnect connects to the Teleport Auth Server directly.
func authConnect(ctx context.Context, params connectParams) (*Client, error) {
dialer := NewDialer(params.cfg.KeepAlivePeriod, params.cfg.DialTimeout)
clt := newClient(params.cfg, dialer, params.tlsConfig)
if err := clt.dialGRPC(ctx, params.addr); err != nil {
return nil, trace.Wrap(err, "failed to connect to addr %v as an auth server", params.addr)
}
return clt, nil
}
// tunnelConnect connects to the Teleport Auth Server through the proxy's reverse tunnel.
func tunnelConnect(ctx context.Context, params connectParams) (*Client, error) {
if params.sshConfig == nil {
return nil, trace.BadParameter("must provide ssh client config")
}
dialer := newTunnelDialer(*params.sshConfig, params.cfg.KeepAlivePeriod, params.cfg.DialTimeout)
clt := newClient(params.cfg, dialer, params.tlsConfig)
if err := clt.dialGRPC(ctx, params.addr); err != nil {
return nil, trace.Wrap(err, "failed to connect to addr %v as a reverse tunnel proxy", params.addr)
}
return clt, nil
}
// proxyConnect connects to the Teleport Auth Server through the proxy.
func proxyConnect(ctx context.Context, params connectParams) (*Client, error) {
if params.sshConfig == nil {
return nil, trace.BadParameter("must provide ssh client config")
}
dialer := NewProxyDialer(*params.sshConfig, params.cfg.KeepAlivePeriod, params.cfg.DialTimeout, params.addr, params.cfg.InsecureAddressDiscovery)
clt := newClient(params.cfg, dialer, params.tlsConfig)
if err := clt.dialGRPC(ctx, params.addr); err != nil {
return nil, trace.Wrap(err, "failed to connect to addr %v as a web proxy", params.addr)
}
return clt, nil
}
// tlsRoutingConnect connects to the Teleport Auth Server through the proxy using TLS Routing.
func tlsRoutingConnect(ctx context.Context, params connectParams) (*Client, error) {
if params.sshConfig == nil {
return nil, trace.BadParameter("must provide ssh client config")
}
dialer := newTLSRoutingTunnelDialer(*params.sshConfig, params.cfg.KeepAlivePeriod, params.cfg.DialTimeout, params.addr, params.cfg.InsecureAddressDiscovery)
clt := newClient(params.cfg, dialer, params.tlsConfig)
if err := clt.dialGRPC(ctx, params.addr); err != nil {
return nil, trace.Wrap(err, "failed to connect to addr %v with TLS Routing dialer", params.addr)
}
return clt, nil
}
// dialerConnect connects to the Teleport Auth Server through a custom dialer.
// The dialer must provide the address in a custom ContextDialerFunc function.
func dialerConnect(ctx context.Context, params connectParams) (*Client, error) {
if params.dialer == nil {
if params.cfg.Dialer == nil {
return nil, trace.BadParameter("must provide dialer to connectParams.dialer or params.cfg.Dialer")
}
params.dialer = params.cfg.Dialer
}
clt := newClient(params.cfg, params.dialer, params.tlsConfig)
// Since the client uses a custom dialer to connect to the server and SNI
// is used for the TLS handshake, the address dialed here is arbitrary.
if err := clt.dialGRPC(ctx, constants.APIDomain); err != nil {
return nil, trace.Wrap(err, "failed to connect using pre-defined dialer")
}
return clt, nil
}
// dialGRPC dials a connection between server and client.
func (c *Client) dialGRPC(ctx context.Context, addr string) error {
dialContext, cancel := context.WithTimeout(ctx, c.c.DialTimeout)
defer cancel()
cb, err := breaker.New(c.c.CircuitBreakerConfig)
if err != nil {
return trace.Wrap(err)
}
var dialOpts []grpc.DialOption
dialOpts = append(dialOpts, grpc.WithContextDialer(c.grpcDialer()))
dialOpts = append(dialOpts,
grpc.WithChainUnaryInterceptor(
otelgrpc.UnaryClientInterceptor(),
metadata.UnaryClientInterceptor,
breaker.UnaryClientInterceptor(cb),
),
grpc.WithChainStreamInterceptor(
otelgrpc.StreamClientInterceptor(),
metadata.StreamClientInterceptor,
breaker.StreamClientInterceptor(cb),
),
)
// Only set transportCredentials if tlsConfig is set. This makes it possible
// to explicitly provide grpc.WithTransportCredentials(insecure.NewCredentials())
// in the client's dial options.
if c.tlsConfig != nil {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(c.tlsConfig)))
}
// must come last, otherwise provided opts may get clobbered by defaults above
dialOpts = append(dialOpts, c.c.DialOpts...)
conn, err := grpc.DialContext(dialContext, addr, dialOpts...)
if err != nil {
return trace.Wrap(err)
}
c.conn = conn
c.grpc = proto.NewAuthServiceClient(c.conn)
c.JoinServiceClient = NewJoinServiceClient(proto.NewJoinServiceClient(c.conn))
return nil
}
// ConfigureALPN configures ALPN SNI cluster routing information in TLS settings allowing for
// allowing to dial auth service through Teleport Proxy directly without using SSH Tunnels.
func ConfigureALPN(tlsConfig *tls.Config, clusterName string) *tls.Config {
if tlsConfig == nil {
return nil
}
if clusterName == "" {
return tlsConfig
}
out := tlsConfig.Clone()
routeInfo := fmt.Sprintf("%s%s", constants.ALPNSNIAuthProtocol, utils.EncodeClusterName(clusterName))
out.NextProtos = append([]string{routeInfo}, out.NextProtos...)
return out
}
// grpcDialer wraps the client's dialer with a grpcDialer.
func (c *Client) grpcDialer() func(ctx context.Context, addr string) (net.Conn, error) {
return func(ctx context.Context, addr string) (net.Conn, error) {
if c.isClosed() {
return nil, trace.ConnectionProblem(nil, "client is closed")
}
conn, err := c.dialer.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, trace.ConnectionProblem(err, "failed to dial: %v", err)
}
return conn, nil
}
}
// waitForConnectionReady waits for the client's grpc connection finish dialing, returning an error
// if the ctx is canceled or the client's gRPC connection enters an unexpected state. This can be used
// alongside the DialInBackground client config option to wait until background dialing has completed.
func (c *Client) waitForConnectionReady(ctx context.Context) error {
for {
if c.conn == nil {
return errors.New("conn was closed")
}
switch state := c.conn.GetState(); state {
case connectivity.Ready:
return nil
case connectivity.TransientFailure, connectivity.Connecting, connectivity.Idle:
// Wait for expected state transitions. For details about grpc.ClientConn state changes
// see https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md
if !c.conn.WaitForStateChange(ctx, state) {
// ctx canceled
return trace.Wrap(ctx.Err())
}
case connectivity.Shutdown:
return trace.Errorf("client gRPC connection entered an unexpected state: %v", state)
}
}
}
// Config contains configuration of the client
type Config struct {
// Addrs is a list of teleport auth/proxy server addresses to dial.
Addrs []string
// Credentials are a list of credentials to use when attempting
// to connect to the server.
Credentials []Credentials
// Dialer is a custom dialer used to dial a server. The Dialer should
// have custom logic to provide an address to the dialer. If set, Dialer
// takes precedence over all other connection options.
Dialer ContextDialer
// DialOpts define options for dialing the client connection.
DialOpts []grpc.DialOption
// DialInBackground specifies to dial the connection in the background
// rather than blocking until the connection is up. A predefined Dialer
// or an auth server address must be provided.
DialInBackground bool
// DialTimeout defines how long to attempt dialing before timing out.
DialTimeout time.Duration
// KeepAlivePeriod defines period between keep alives.
KeepAlivePeriod time.Duration
// KeepAliveCount specifies the amount of missed keep alives
// to wait for before declaring the connection as broken.
KeepAliveCount int
// The web proxy uses a self-signed TLS certificate by default, which
// requires this field to be set. If the web proxy was provided with
// signed TLS certificates, this field should not be set.
InsecureAddressDiscovery bool
// ALPNSNIAuthDialClusterName if present the client will include ALPN SNI routing information in TLS Hello message
// allowing to dial auth service through Teleport Proxy directly without using SSH Tunnels.
ALPNSNIAuthDialClusterName string
// CircuitBreakerConfig defines how the circuit breaker should behave.
CircuitBreakerConfig breaker.Config
// Context is the base context to use for dialing. If not provided context.Background is used
Context context.Context
}
// CheckAndSetDefaults checks and sets default config values.
func (c *Config) CheckAndSetDefaults() error {
if len(c.Credentials) == 0 {
return trace.BadParameter("missing connection credentials")
}
if c.KeepAlivePeriod == 0 {
c.KeepAlivePeriod = defaults.ServerKeepAliveTTL()
}
if c.KeepAliveCount == 0 {
c.KeepAliveCount = defaults.KeepAliveCountMax
}
if c.DialTimeout == 0 {
c.DialTimeout = defaults.DefaultDialTimeout
}
if c.CircuitBreakerConfig.Trip == nil || c.CircuitBreakerConfig.IsSuccessful == nil {
c.CircuitBreakerConfig = breaker.DefaultBreakerConfig(clockwork.NewRealClock())
}
if c.Context == nil {
c.Context = context.Background()
}
c.DialOpts = append(c.DialOpts, grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: c.KeepAlivePeriod,
Timeout: c.KeepAlivePeriod * time.Duration(c.KeepAliveCount),
PermitWithoutStream: true,
}))
if !c.DialInBackground {
c.DialOpts = append(c.DialOpts, grpc.WithBlock())
}
return nil
}
// Config returns the tls.Config the client connected with.
func (c *Client) Config() *tls.Config {
return c.tlsConfig
}
// Dialer returns the ContextDialer the client connected with.
func (c *Client) Dialer() ContextDialer {
return c.dialer
}
// GetConnection returns GRPC connection.
func (c *Client) GetConnection() *grpc.ClientConn {
return c.conn
}
// Close closes the Client connection to the auth server.
func (c *Client) Close() error {
if c.setClosed() && c.conn != nil {
err := c.conn.Close()
c.conn = nil
return trace.Wrap(err)
}
return nil
}
// isClosed returns whether the client is marked as closed.
func (c *Client) isClosed() bool {
return atomic.LoadInt32(c.closedFlag) == 1
}
// setClosed marks the client as closed and returns true if it was open.
func (c *Client) setClosed() bool {
return atomic.CompareAndSwapInt32(c.closedFlag, 0, 1)
}
// WithCallOptions returns a copy of the client with the given call options set.
// This function should be used for chaining - client.WithCallOptions().Ping()
func (c *Client) WithCallOptions(opts ...grpc.CallOption) *Client {
clt := *c
clt.callOpts = append(clt.callOpts, opts...)
return &clt
}
// Ping gets basic info about the auth server.
func (c *Client) Ping(ctx context.Context) (proto.PingResponse, error) {
rsp, err := c.grpc.Ping(ctx, &proto.PingRequest{}, c.callOpts...)
if err != nil {
return proto.PingResponse{}, trail.FromGRPC(err)
}
return *rsp, nil
}
// UpdateRemoteCluster updates remote cluster from the specified value.
func (c *Client) UpdateRemoteCluster(ctx context.Context, rc types.RemoteCluster) error {
rcV3, ok := rc.(*types.RemoteClusterV3)
if !ok {
return trace.BadParameter("unsupported remote cluster type %T", rcV3)
}
_, err := c.grpc.UpdateRemoteCluster(ctx, rcV3, c.callOpts...)
return trail.FromGRPC(err)
}
// CreateUser creates a new user from the specified descriptor.
func (c *Client) CreateUser(ctx context.Context, user types.User) error {
userV2, ok := user.(*types.UserV2)
if !ok {
return trace.BadParameter("unsupported user type %T", user)
}
_, err := c.grpc.CreateUser(ctx, userV2, c.callOpts...)
return trail.FromGRPC(err)
}
// UpdateUser updates an existing user in a backend.
func (c *Client) UpdateUser(ctx context.Context, user types.User) error {
userV2, ok := user.(*types.UserV2)
if !ok {
return trace.BadParameter("unsupported user type %T", user)
}
_, err := c.grpc.UpdateUser(ctx, userV2, c.callOpts...)
return trail.FromGRPC(err)
}
// GetUser returns a list of usernames registered in the system.
// withSecrets controls whether authentication details are returned.
func (c *Client) GetUser(name string, withSecrets bool) (types.User, error) {
if name == "" {
return nil, trace.BadParameter("missing username")
}
user, err := c.grpc.GetUser(context.TODO(), &proto.GetUserRequest{
Name: name,
WithSecrets: withSecrets,
}, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return user, nil
}
// GetCurrentUser returns current user as seen by the server.
// Useful especially in the context of remote clusters which perform role and trait mapping.
func (c *Client) GetCurrentUser(ctx context.Context) (types.User, error) {
currentUser, err := c.grpc.GetCurrentUser(ctx, &empty.Empty{})
if err != nil {
return nil, trail.FromGRPC(err)
}
return currentUser, nil
}
// GetUsers returns a list of users.
// withSecrets controls whether authentication details are returned.
func (c *Client) GetUsers(withSecrets bool) ([]types.User, error) {
stream, err := c.grpc.GetUsers(context.TODO(), &proto.GetUsersRequest{
WithSecrets: withSecrets,
}, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
var users []types.User
for user, err := stream.Recv(); err != io.EOF; user, err = stream.Recv() {
if err != nil {
return nil, trail.FromGRPC(err)
}
users = append(users, user)
}
return users, nil
}
// DeleteUser deletes a user by name.
func (c *Client) DeleteUser(ctx context.Context, user string) error {
req := &proto.DeleteUserRequest{Name: user}
_, err := c.grpc.DeleteUser(ctx, req, c.callOpts...)
return trail.FromGRPC(err)
}
// GenerateUserCerts takes the public key in the OpenSSH `authorized_keys` plain
// text format, signs it using User Certificate Authority signing key and
// returns the resulting certificates.
func (c *Client) GenerateUserCerts(ctx context.Context, req proto.UserCertsRequest) (*proto.Certs, error) {
certs, err := c.grpc.GenerateUserCerts(ctx, &req, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return certs, nil
}
// GenerateHostCerts generates host certificates.
func (c *Client) GenerateHostCerts(ctx context.Context, req *proto.HostCertsRequest) (*proto.Certs, error) {
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
certs, err := c.grpc.GenerateHostCerts(ctx, req, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return certs, nil
}
// UnstableAssertSystemRole is not a stable part of the public API. Used by older
// instances to prove that they hold a given system role.
//
// DELETE IN: 11.0 (server side method should continue to exist until 12.0 for back-compat reasons,
// but v11 clients should no longer need this method)
func (c *Client) UnstableAssertSystemRole(ctx context.Context, req proto.UnstableSystemRoleAssertion) error {
_, err := c.grpc.UnstableAssertSystemRole(ctx, &req, c.callOpts...)
return trail.FromGRPC(err)
}
// EmitAuditEvent sends an auditable event to the auth server.
func (c *Client) EmitAuditEvent(ctx context.Context, event events.AuditEvent) error {
grpcEvent, err := events.ToOneOf(event)
if err != nil {
return trace.Wrap(err)
}
_, err = c.grpc.EmitAuditEvent(ctx, grpcEvent, c.callOpts...)
if err != nil {
return trail.FromGRPC(err)
}
return nil
}
// RotateUserTokenSecrets rotates secrets for a given tokenID.
// It gets called every time a user fetches 2nd-factor secrets during registration attempt.
// This ensures that an attacker that gains the ResetPasswordToken link can not view it,
// extract the OTP key from the QR code, then allow the user to signup with
// the same OTP token.
func (c *Client) RotateUserTokenSecrets(ctx context.Context, tokenID string) (types.UserTokenSecrets, error) {
secrets, err := c.grpc.RotateResetPasswordTokenSecrets(ctx, &proto.RotateUserTokenSecretsRequest{
TokenID: tokenID,
}, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return secrets, nil
}
// GetResetPasswordToken returns a reset password token for the specified tokenID.
func (c *Client) GetResetPasswordToken(ctx context.Context, tokenID string) (types.UserToken, error) {
token, err := c.grpc.GetResetPasswordToken(ctx, &proto.GetResetPasswordTokenRequest{
TokenID: tokenID,
}, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return token, nil
}
// CreateResetPasswordToken creates reset password token.
func (c *Client) CreateResetPasswordToken(ctx context.Context, req *proto.CreateResetPasswordTokenRequest) (types.UserToken, error) {
token, err := c.grpc.CreateResetPasswordToken(ctx, req, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return token, nil
}
// CreateBot creates a new bot from the specified descriptor.
func (c *Client) CreateBot(ctx context.Context, req *proto.CreateBotRequest) (*proto.CreateBotResponse, error) {
response, err := c.grpc.CreateBot(ctx, req, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return response, nil
}
// DeleteBot deletes a bot and associated resources.
func (c *Client) DeleteBot(ctx context.Context, botName string) error {
_, err := c.grpc.DeleteBot(ctx, &proto.DeleteBotRequest{
Name: botName,
}, c.callOpts...)
return trail.FromGRPC(err)
}
// GetBotUsers fetches all bot users.
func (c *Client) GetBotUsers(ctx context.Context) ([]types.User, error) {
stream, err := c.grpc.GetBotUsers(ctx, &proto.GetBotUsersRequest{}, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
var users []types.User
for user, err := stream.Recv(); err != io.EOF; user, err = stream.Recv() {
if err != nil {
return nil, trail.FromGRPC(err)
}
users = append(users, user)
}
return users, nil
}
// GetAccessRequests retrieves a list of all access requests matching the provided filter.
func (c *Client) GetAccessRequests(ctx context.Context, filter types.AccessRequestFilter) ([]types.AccessRequest, error) {
stream, err := c.grpc.GetAccessRequestsV2(ctx, &filter, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
var reqs []types.AccessRequest
for {
req, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
err := trail.FromGRPC(err)
if trace.IsNotImplemented(err) {
return c.getAccessRequestsLegacy(ctx, filter)
}
return nil, err
}
reqs = append(reqs, req)
}
return reqs, nil
}
// getAccessRequestsLegacy retrieves a list of all access requests matching the provided filter using the old access request API.
//
// DELETE IN: 11.0.0. Used for compatibility with old auth servers that don't support the GetAccessRequestsV2 RPC.
func (c *Client) getAccessRequestsLegacy(ctx context.Context, filter types.AccessRequestFilter) ([]types.AccessRequest, error) {
requests, err := c.grpc.GetAccessRequests(ctx, &filter, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
reqs := make([]types.AccessRequest, len(requests.AccessRequests))
for i, request := range requests.AccessRequests {
reqs[i] = request
}
return reqs, nil
}
// CreateAccessRequest registers a new access request with the auth server.
func (c *Client) CreateAccessRequest(ctx context.Context, req types.AccessRequest) error {
r, ok := req.(*types.AccessRequestV3)
if !ok {
return trace.BadParameter("unexpected access request type %T", req)
}
_, err := c.grpc.CreateAccessRequest(ctx, r, c.callOpts...)
return trail.FromGRPC(err)
}
// DeleteAccessRequest deletes an access request.
func (c *Client) DeleteAccessRequest(ctx context.Context, reqID string) error {
_, err := c.grpc.DeleteAccessRequest(ctx, &proto.RequestID{ID: reqID}, c.callOpts...)
return trail.FromGRPC(err)
}
// SetAccessRequestState updates the state of an existing access request.
func (c *Client) SetAccessRequestState(ctx context.Context, params types.AccessRequestUpdate) error {
setter := proto.RequestStateSetter{
ID: params.RequestID,
State: params.State,
Reason: params.Reason,
Annotations: params.Annotations,
Roles: params.Roles,
}
if d := utils.GetDelegator(ctx); d != "" {
setter.Delegator = d
}
_, err := c.grpc.SetAccessRequestState(ctx, &setter, c.callOpts...)
return trail.FromGRPC(err)
}
// SubmitAccessReview applies a review to a request and returns the post-application state.
func (c *Client) SubmitAccessReview(ctx context.Context, params types.AccessReviewSubmission) (types.AccessRequest, error) {
req, err := c.grpc.SubmitAccessReview(ctx, ¶ms, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return req, nil
}
// GetAccessCapabilities requests the access capabilities of a user.
func (c *Client) GetAccessCapabilities(ctx context.Context, req types.AccessCapabilitiesRequest) (*types.AccessCapabilities, error) {
caps, err := c.grpc.GetAccessCapabilities(ctx, &req, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return caps, nil
}
// GetPluginData loads all plugin data matching the supplied filter.
func (c *Client) GetPluginData(ctx context.Context, filter types.PluginDataFilter) ([]types.PluginData, error) {
seq, err := c.grpc.GetPluginData(ctx, &filter, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
data := make([]types.PluginData, 0, len(seq.PluginData))
for _, d := range seq.PluginData {
data = append(data, d)
}
return data, nil
}
// UpdatePluginData updates a per-resource PluginData entry.
func (c *Client) UpdatePluginData(ctx context.Context, params types.PluginDataUpdateParams) error {
_, err := c.grpc.UpdatePluginData(ctx, ¶ms, c.callOpts...)
return trail.FromGRPC(err)
}
// AcquireSemaphore acquires lease with requested resources from semaphore.
func (c *Client) AcquireSemaphore(ctx context.Context, params types.AcquireSemaphoreRequest) (*types.SemaphoreLease, error) {
lease, err := c.grpc.AcquireSemaphore(ctx, ¶ms, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return lease, nil
}
// KeepAliveSemaphoreLease updates semaphore lease.
func (c *Client) KeepAliveSemaphoreLease(ctx context.Context, lease types.SemaphoreLease) error {
_, err := c.grpc.KeepAliveSemaphoreLease(ctx, &lease, c.callOpts...)
return trail.FromGRPC(err)
}
// CancelSemaphoreLease cancels semaphore lease early.
func (c *Client) CancelSemaphoreLease(ctx context.Context, lease types.SemaphoreLease) error {
_, err := c.grpc.CancelSemaphoreLease(ctx, &lease, c.callOpts...)
return trail.FromGRPC(err)
}
// GetSemaphores returns a list of all semaphores matching the supplied filter.
func (c *Client) GetSemaphores(ctx context.Context, filter types.SemaphoreFilter) ([]types.Semaphore, error) {
rsp, err := c.grpc.GetSemaphores(ctx, &filter, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
sems := make([]types.Semaphore, 0, len(rsp.Semaphores))
for _, s := range rsp.Semaphores {
sems = append(sems, s)
}
return sems, nil
}
// DeleteSemaphore deletes a semaphore matching the supplied filter.
func (c *Client) DeleteSemaphore(ctx context.Context, filter types.SemaphoreFilter) error {
_, err := c.grpc.DeleteSemaphore(ctx, &filter, c.callOpts...)
return trail.FromGRPC(err)
}
// UpsertKubeService is used by kubernetes services to report their presence
// to other auth servers in form of hearbeat expiring after ttl period.
func (c *Client) UpsertKubeService(ctx context.Context, s types.Server) error {
server, ok := s.(*types.ServerV2)
if !ok {
return trace.BadParameter("invalid type %T, expected *types.ServerV2", server)
}
_, err := c.grpc.UpsertKubeService(ctx, &proto.UpsertKubeServiceRequest{
Server: server,
}, c.callOpts...)
return trace.Wrap(err)
}
// UpsertKubeServiceV2 is used by kubernetes services to report their presence
// to other auth servers in form of hearbeat expiring after ttl period.
func (c *Client) UpsertKubeServiceV2(ctx context.Context, s types.Server) (*types.KeepAlive, error) {
server, ok := s.(*types.ServerV2)
if !ok {
return nil, trace.BadParameter("invalid type %T, expected *types.ServerV2", server)
}
keepAlive, err := c.grpc.UpsertKubeServiceV2(ctx, &proto.UpsertKubeServiceRequest{Server: server}, c.callOpts...)
if err != nil {
return nil, trail.FromGRPC(err)
}
return keepAlive, nil
}
// GetKubeServices returns the list of kubernetes services registered in the
// cluster.
func (c *Client) GetKubeServices(ctx context.Context) ([]types.Server, error) {
resources, err := GetResourcesWithFilters(ctx, c, proto.ListResourcesRequest{
Namespace: defaults.Namespace,
ResourceType: types.KindKubeService,
})
if err != nil {
// Underlying ListResources for kube service was not available, use fallback.
//
// DELETE IN 11.0.0
if trace.IsNotImplemented(err) {
return c.getKubeServicesFallback(ctx)
}
return nil, trace.Wrap(err)
}
servers, err := types.ResourcesWithLabels(resources).AsServers()
if err != nil {
return nil, trace.Wrap(err)
}