-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
clients.go
1241 lines (1105 loc) · 49.2 KB
/
clients.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 2021 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 cloud
import (
"context"
"io"
"sync"
"time"
gcpcredentials "cloud.google.com/go/iam/credentials/apiv1"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v2"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/mysql/armmysql"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresql"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/subscription/armsubscription"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
awssession "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/aws/aws-sdk-go/service/eks/eksiface"
"github.com/aws/aws-sdk-go/service/elasticache"
"github.com/aws/aws-sdk-go/service/elasticache/elasticacheiface"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/iam/iamiface"
"github.com/aws/aws-sdk-go/service/memorydb"
"github.com/aws/aws-sdk-go/service/memorydb/memorydbiface"
"github.com/aws/aws-sdk-go/service/opensearchservice"
"github.com/aws/aws-sdk-go/service/opensearchservice/opensearchserviceiface"
"github.com/aws/aws-sdk-go/service/rds"
"github.com/aws/aws-sdk-go/service/rds/rdsiface"
"github.com/aws/aws-sdk-go/service/redshift"
"github.com/aws/aws-sdk-go/service/redshift/redshiftiface"
"github.com/aws/aws-sdk-go/service/redshiftserverless"
"github.com/aws/aws-sdk-go/service/redshiftserverless/redshiftserverlessiface"
"github.com/aws/aws-sdk-go/service/secretsmanager"
"github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/service/ssm/ssmiface"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/aws/aws-sdk-go/service/sts/stsiface"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/gravitational/teleport/api/types"
libcloudaws "github.com/gravitational/teleport/lib/cloud/aws"
"github.com/gravitational/teleport/lib/cloud/azure"
"github.com/gravitational/teleport/lib/cloud/gcp"
"github.com/gravitational/teleport/lib/utils"
)
// Clients provides interface for obtaining cloud provider clients.
type Clients interface {
// GetInstanceMetadataClient returns instance metadata client based on which
// cloud provider Teleport is running on, if any.
GetInstanceMetadataClient(ctx context.Context) (InstanceMetadata, error)
// GCPClients is an interface for providing GCP API clients.
GCPClients
// AWSClients is an interface for providing AWS API clients.
AWSClients
// AzureClients is an interface for Azure-specific API clients
AzureClients
// Closer closes all initialized clients.
io.Closer
}
// GCPClients is an interface for providing GCP API clients.
type GCPClients interface {
// GetGCPIAMClient returns GCP IAM client.
GetGCPIAMClient(context.Context) (*gcpcredentials.IamCredentialsClient, error)
// GetGCPSQLAdminClient returns GCP Cloud SQL Admin client.
GetGCPSQLAdminClient(context.Context) (gcp.SQLAdminClient, error)
// GetGCPGKEClient returns GKE client.
GetGCPGKEClient(context.Context) (gcp.GKEClient, error)
// GetGCPInstancesClient returns instances client.
GetGCPInstancesClient(context.Context) (gcp.InstancesClient, error)
}
// AWSClients is an interface for providing AWS API clients.
type AWSClients interface {
// GetAWSSession returns AWS session for the specified region and any role(s).
GetAWSSession(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (*awssession.Session, error)
// GetAWSRDSClient returns AWS RDS client for the specified region.
GetAWSRDSClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (rdsiface.RDSAPI, error)
// GetAWSRedshiftClient returns AWS Redshift client for the specified region.
GetAWSRedshiftClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (redshiftiface.RedshiftAPI, error)
// GetAWSRedshiftServerlessClient returns AWS Redshift Serverless client for the specified region.
GetAWSRedshiftServerlessClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (redshiftserverlessiface.RedshiftServerlessAPI, error)
// GetAWSElastiCacheClient returns AWS ElastiCache client for the specified region.
GetAWSElastiCacheClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (elasticacheiface.ElastiCacheAPI, error)
// GetAWSMemoryDBClient returns AWS MemoryDB client for the specified region.
GetAWSMemoryDBClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (memorydbiface.MemoryDBAPI, error)
// GetAWSOpenSearchClient returns AWS OpenSearch client for the specified region.
GetAWSOpenSearchClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (opensearchserviceiface.OpenSearchServiceAPI, error)
// GetAWSSecretsManagerClient returns AWS Secrets Manager client for the specified region.
GetAWSSecretsManagerClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (secretsmanageriface.SecretsManagerAPI, error)
// GetAWSIAMClient returns AWS IAM client for the specified region.
GetAWSIAMClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (iamiface.IAMAPI, error)
// GetAWSSTSClient returns AWS STS client for the specified region.
GetAWSSTSClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (stsiface.STSAPI, error)
// GetAWSEC2Client returns AWS EC2 client for the specified region.
GetAWSEC2Client(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (ec2iface.EC2API, error)
// GetAWSSSMClient returns AWS SSM client for the specified region.
GetAWSSSMClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (ssmiface.SSMAPI, error)
// GetAWSEKSClient returns AWS EKS client for the specified region.
GetAWSEKSClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (eksiface.EKSAPI, error)
}
// AzureClients is an interface for Azure-specific API clients
type AzureClients interface {
// GetAzureCredential returns Azure default token credential chain.
GetAzureCredential() (azcore.TokenCredential, error)
// GetAzureMySQLClient returns Azure MySQL client for the specified subscription.
GetAzureMySQLClient(subscription string) (azure.DBServersClient, error)
// GetAzurePostgresClient returns Azure Postgres client for the specified subscription.
GetAzurePostgresClient(subscription string) (azure.DBServersClient, error)
// GetAzureSubscriptionClient returns an Azure Subscriptions client
GetAzureSubscriptionClient() (*azure.SubscriptionClient, error)
// GetAzureRedisClient returns an Azure Redis client for the given subscription.
GetAzureRedisClient(subscription string) (azure.RedisClient, error)
// GetAzureRedisEnterpriseClient returns an Azure Redis Enterprise client for the given subscription.
GetAzureRedisEnterpriseClient(subscription string) (azure.RedisEnterpriseClient, error)
// GetAzureKubernetesClient returns an Azure AKS client for the specified subscription.
GetAzureKubernetesClient(subscription string) (azure.AKSClient, error)
// GetAzureVirtualMachinesClient returns an Azure Virtual Machines client for the given subscription.
GetAzureVirtualMachinesClient(subscription string) (azure.VirtualMachinesClient, error)
// GetAzureSQLServerClient returns an Azure SQL Server client for the
// specified subscription.
GetAzureSQLServerClient(subscription string) (azure.SQLServerClient, error)
// GetAzureManagedSQLServerClient returns an Azure ManagedSQL Server client
// for the specified subscription.
GetAzureManagedSQLServerClient(subscription string) (azure.ManagedSQLServerClient, error)
// GetAzureMySQLFlexServersClient returns an Azure MySQL Flexible Server client for the
// specified subscription.
GetAzureMySQLFlexServersClient(subscription string) (azure.MySQLFlexServersClient, error)
// GetAzurePostgresFlexServersClient returns an Azure PostgreSQL Flexible Server client for the
// specified subscription.
GetAzurePostgresFlexServersClient(subscription string) (azure.PostgresFlexServersClient, error)
// GetAzureRunCommandClient returns an Azure Run Command client for the given subscription.
GetAzureRunCommandClient(subscription string) (azure.RunCommandClient, error)
}
type clientConstructor[T any] func(context.Context) (T, error)
// clientCache is a struct that holds a cloud client that will only be
// initialized once.
type clientCache[T any] struct {
makeClient clientConstructor[T]
client T
err error
once sync.Once
}
// newClientCache creates a new client cache.
func newClientCache[T any](makeClient clientConstructor[T]) *clientCache[T] {
return &clientCache[T]{makeClient: makeClient}
}
// GetClient gets the client, initializing it if necessary.
func (c *clientCache[T]) GetClient(ctx context.Context) (T, error) {
c.once.Do(func() {
c.client, c.err = c.makeClient(ctx)
})
return c.client, trace.Wrap(c.err)
}
func newAzureClients() (*azureClients, error) {
azClients := &azureClients{
azureMySQLClients: make(map[string]azure.DBServersClient),
azurePostgresClients: make(map[string]azure.DBServersClient),
azureKubernetesClient: make(map[string]azure.AKSClient),
}
var err error
azClients.azureRedisClients, err = azure.NewClientMap(azure.NewRedisClient)
if err != nil {
return nil, trace.Wrap(err)
}
azClients.azureRedisEnterpriseClients, err = azure.NewClientMap(azure.NewRedisEnterpriseClient)
if err != nil {
return nil, trace.Wrap(err)
}
azClients.azureVirtualMachinesClients, err = azure.NewClientMap(azure.NewVirtualMachinesClient)
if err != nil {
return nil, trace.Wrap(err)
}
azClients.azureSQLServerClients, err = azure.NewClientMap(azure.NewSQLClient)
if err != nil {
return nil, trace.Wrap(err)
}
azClients.azureManagedSQLServerClients, err = azure.NewClientMap(azure.NewManagedSQLClient)
if err != nil {
return nil, trace.Wrap(err)
}
azClients.azureMySQLFlexServersClients, err = azure.NewClientMap(azure.NewMySQLFlexServersClient)
if err != nil {
return nil, trace.Wrap(err)
}
azClients.azurePostgresFlexServersClients, err = azure.NewClientMap(azure.NewPostgresFlexServersClient)
if err != nil {
return nil, trace.Wrap(err)
}
azClients.azureRunCommandClients, err = azure.NewClientMap(azure.NewRunCommandClient)
if err != nil {
return nil, trace.Wrap(err)
}
return azClients, nil
}
// ClientsOption allows setting options as functional arguments to cloudClients.
type ClientsOption func(cfg *cloudClients)
// NewClients returns a new instance of cloud clients retriever.
func NewClients(opts ...ClientsOption) (Clients, error) {
awsSessionsCache, err := utils.NewFnCache(utils.FnCacheConfig{
TTL: 15 * time.Minute,
})
if err != nil {
return nil, trace.Wrap(err)
}
azClients, err := newAzureClients()
if err != nil {
return nil, trace.Wrap(err)
}
cloudClients := &cloudClients{
awsSessionsCache: awsSessionsCache,
gcpClients: gcpClients{
gcpSQLAdmin: newClientCache[gcp.SQLAdminClient](gcp.NewSQLAdminClient),
gcpGKE: newClientCache[gcp.GKEClient](gcp.NewGKEClient),
gcpInstances: newClientCache[gcp.InstancesClient](gcp.NewInstancesClient),
},
azureClients: azClients,
}
for _, opt := range opts {
opt(cloudClients)
}
return cloudClients, nil
}
// cloudClients implements Clients
var _ Clients = (*cloudClients)(nil)
// WithAWSIntegrationSessionProvider sets an integration session generator for AWS apis.
// If a client is requested for a specific Integration, instead of using the ambient credentials, this generator is used to fetch the AWS Session.
func WithAWSIntegrationSessionProvider(sessionProvider AWSIntegrationSessionProvider) func(*cloudClients) {
return func(cc *cloudClients) {
cc.awsIntegrationSessionProviderFn = sessionProvider
}
}
// AWSIntegrationSessionProvider defines a function that creates an [awssession.Session] from a Region and an Integration.
// This is used to generate aws sessions for clients that must use an Integration instead of ambient credentials.
type AWSIntegrationSessionProvider func(ctx context.Context, region string, integration string) (*awssession.Session, error)
type awsSessionCacheKey struct {
region string
integration string
roleARN string
externalID string
}
type cloudClients struct {
// awsSessionsCache is a cache of AWS sessions, where the cache key is
// an instance of awsSessionCacheKey.
awsSessionsCache *utils.FnCache
// awsIntegrationSessionProviderFn is a AWS Session Generator that uses an Integration to generate an AWS Session.
awsIntegrationSessionProviderFn AWSIntegrationSessionProvider
// instanceMetadata is the cached instance metadata client.
instanceMetadata InstanceMetadata
// gcpClients contains GCP-specific clients.
gcpClients
// azureClients contains Azure-specific clients.
*azureClients
// mtx is used for locking.
mtx sync.RWMutex
}
// gcpClients contains GCP-specific clients.
type gcpClients struct {
// gcpIAM is the cached GCP IAM client.
gcpIAM *gcpcredentials.IamCredentialsClient
// gcpSQLAdmin is the cached GCP Cloud SQL Admin client.
gcpSQLAdmin *clientCache[gcp.SQLAdminClient]
// gcpGKE is the cached GCP Cloud GKE client.
gcpGKE *clientCache[gcp.GKEClient]
// gcpInstances is the cached GCP instances client.
gcpInstances *clientCache[gcp.InstancesClient]
}
// azureClients contains Azure-specific clients.
type azureClients struct {
// azureCredential is the cached Azure credential.
azureCredential azcore.TokenCredential
// azureMySQLClients is the cached Azure MySQL Server clients.
azureMySQLClients map[string]azure.DBServersClient
// azurePostgresClients is the cached Azure Postgres Server clients.
azurePostgresClients map[string]azure.DBServersClient
// azureSubscriptionsClient is the cached Azure Subscriptions client.
azureSubscriptionsClient *azure.SubscriptionClient
// azureRedisClients contains the cached Azure Redis clients.
azureRedisClients azure.ClientMap[azure.RedisClient]
// azureRedisEnterpriseClients contains the cached Azure Redis Enterprise clients.
azureRedisEnterpriseClients azure.ClientMap[azure.RedisEnterpriseClient]
// azureKubernetesClient is the cached Azure Kubernetes client.
azureKubernetesClient map[string]azure.AKSClient
// azureVirtualMachinesClients contains the cached Azure Virtual Machines clients.
azureVirtualMachinesClients azure.ClientMap[azure.VirtualMachinesClient]
// azureSQLServerClient is the cached Azure SQL Server client.
azureSQLServerClients azure.ClientMap[azure.SQLServerClient]
// azureManagedSQLServerClient is the cached Azure Managed SQL Server
// client.
azureManagedSQLServerClients azure.ClientMap[azure.ManagedSQLServerClient]
// azureMySQLFlexServersClients is the cached Azure MySQL Flexible Server
// client.
azureMySQLFlexServersClients azure.ClientMap[azure.MySQLFlexServersClient]
// azurePostgresFlexServersClients is the cached Azure PostgreSQL Flexible Server
// client.
azurePostgresFlexServersClients azure.ClientMap[azure.PostgresFlexServersClient]
// azureRunCommandClients contains the cached Azure Run Command clients.
azureRunCommandClients azure.ClientMap[azure.RunCommandClient]
}
// credentialsSource defines where the credentials must come from.
type credentialsSource int
const (
// credentialsSourceAmbient uses the default Cloud SDK method to load the credentials.
credentialsSourceAmbient = iota + 1
// CredentialsSourceIntegration uses an Integration to load the credentials.
credentialsSourceIntegration
)
// awsAssumeRoleOpts a struct of additional options for assuming an AWS role
// when construction an underlying AWS session.
type awsAssumeRoleOpts struct {
// baseSession is a session to use instead of the default session for an
// AWS region, which is used to enable role chaining.
baseSession *awssession.Session
// assumeRoleARN is the AWS IAM Role ARN to assume.
assumeRoleARN string
// assumeRoleExternalID is used to assume an external AWS IAM Role.
assumeRoleExternalID string
// credentialsSource describes which source to use to fetch credentials.
credentialsSource credentialsSource
// integration is the name of the integration to be used to fetch the credentials.
integration string
}
func (a *awsAssumeRoleOpts) checkAndSetDefaults() error {
switch a.credentialsSource {
case credentialsSourceAmbient:
if a.integration != "" {
return trace.BadParameter("integration and ambient credentials cannot be used at the same time")
}
case credentialsSourceIntegration:
if a.integration == "" {
return trace.BadParameter("missing integration name")
}
default:
return trace.BadParameter("missing credentials source (ambient or integration)")
}
return nil
}
// AWSAssumeRoleOptionFn is an option function for setting additional options
// when getting an AWS session.
type AWSAssumeRoleOptionFn func(*awsAssumeRoleOpts)
// WithAssumeRole configures options needed for assuming an AWS role.
func WithAssumeRole(roleARN, externalID string) AWSAssumeRoleOptionFn {
return func(options *awsAssumeRoleOpts) {
options.assumeRoleARN = roleARN
options.assumeRoleExternalID = externalID
}
}
// WithAssumeRoleFromAWSMeta extracts options needed from AWS metadata for
// assuming an AWS role.
func WithAssumeRoleFromAWSMeta(meta types.AWS) AWSAssumeRoleOptionFn {
return WithAssumeRole(meta.AssumeRoleARN, meta.ExternalID)
}
// WithChainedAssumeRole sets a role to assume with a base session to use
// for assuming the role, which enables role chaining.
func WithChainedAssumeRole(session *awssession.Session, roleARN, externalID string) AWSAssumeRoleOptionFn {
return func(options *awsAssumeRoleOpts) {
options.baseSession = session
options.assumeRoleARN = roleARN
options.assumeRoleExternalID = externalID
}
}
// WithCredentialsMaybeIntegration sets the credential source to be
// - ambient if the integration is an empty string
// - integration, otherwise
func WithCredentialsMaybeIntegration(integration string) AWSAssumeRoleOptionFn {
if integration != "" {
return withIntegrationCredentials(integration)
}
return WithAmbientCredentials()
}
// withIntegrationCredentials configures options with an Integration that must be used to fetch Credentials to assume a role.
// This prevents the usage of AWS environment credentials.
func withIntegrationCredentials(integration string) AWSAssumeRoleOptionFn {
return func(options *awsAssumeRoleOpts) {
options.credentialsSource = credentialsSourceIntegration
options.integration = integration
}
}
// WithAmbientCredentials configures options to use the ambient credentials.
func WithAmbientCredentials() AWSAssumeRoleOptionFn {
return func(options *awsAssumeRoleOpts) {
options.credentialsSource = credentialsSourceAmbient
}
}
// GetAWSSession returns AWS session for the specified region, optionally
// assuming AWS IAM Roles.
func (c *cloudClients) GetAWSSession(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (*awssession.Session, error) {
var options awsAssumeRoleOpts
for _, opt := range opts {
opt(&options)
}
var err error
if options.baseSession == nil {
options.baseSession, err = c.getAWSSessionForRegion(region, options)
if err != nil {
return nil, trace.Wrap(err)
}
}
if options.assumeRoleARN == "" {
return options.baseSession, nil
}
return c.getAWSSessionForRole(ctx, region, options)
}
// GetAWSRDSClient returns AWS RDS client for the specified region.
func (c *cloudClients) GetAWSRDSClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (rdsiface.RDSAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return rds.New(session), nil
}
// GetAWSRedshiftClient returns AWS Redshift client for the specified region.
func (c *cloudClients) GetAWSRedshiftClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (redshiftiface.RedshiftAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return redshift.New(session), nil
}
// GetAWSRedshiftServerlessClient returns AWS Redshift Serverless client for the specified region.
func (c *cloudClients) GetAWSRedshiftServerlessClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (redshiftserverlessiface.RedshiftServerlessAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return redshiftserverless.New(session), nil
}
// GetAWSElastiCacheClient returns AWS ElastiCache client for the specified region.
func (c *cloudClients) GetAWSElastiCacheClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (elasticacheiface.ElastiCacheAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return elasticache.New(session), nil
}
// GetAWSOpenSearchClient returns AWS OpenSearch client for the specified region.
func (c *cloudClients) GetAWSOpenSearchClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (opensearchserviceiface.OpenSearchServiceAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return opensearchservice.New(session), nil
}
// GetAWSMemoryDBClient returns AWS MemoryDB client for the specified region.
func (c *cloudClients) GetAWSMemoryDBClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (memorydbiface.MemoryDBAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return memorydb.New(session), nil
}
// GetAWSSecretsManagerClient returns AWS Secrets Manager client for the specified region.
func (c *cloudClients) GetAWSSecretsManagerClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (secretsmanageriface.SecretsManagerAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return secretsmanager.New(session), nil
}
// GetAWSIAMClient returns AWS IAM client for the specified region.
func (c *cloudClients) GetAWSIAMClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (iamiface.IAMAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return iam.New(session), nil
}
// GetAWSSTSClient returns AWS STS client for the specified region.
func (c *cloudClients) GetAWSSTSClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (stsiface.STSAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return sts.New(session), nil
}
// GetAWSEC2Client returns AWS EC2 client for the specified region.
func (c *cloudClients) GetAWSEC2Client(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (ec2iface.EC2API, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return ec2.New(session), nil
}
// GetAWSSSMClient returns AWS SSM client for the specified region.
func (c *cloudClients) GetAWSSSMClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (ssmiface.SSMAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return ssm.New(session), nil
}
// GetAWSEKSClient returns AWS EKS client for the specified region.
func (c *cloudClients) GetAWSEKSClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (eksiface.EKSAPI, error) {
session, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return eks.New(session), nil
}
// GetGCPIAMClient returns GCP IAM client.
func (c *cloudClients) GetGCPIAMClient(ctx context.Context) (*gcpcredentials.IamCredentialsClient, error) {
c.mtx.RLock()
if c.gcpIAM != nil {
defer c.mtx.RUnlock()
return c.gcpIAM, nil
}
c.mtx.RUnlock()
return c.initGCPIAMClient(ctx)
}
// GetGCPSQLAdminClient returns GCP Cloud SQL Admin client.
func (c *cloudClients) GetGCPSQLAdminClient(ctx context.Context) (gcp.SQLAdminClient, error) {
return c.gcpSQLAdmin.GetClient(ctx)
}
// GetInstanceMetadata returns the instance metadata.
func (c *cloudClients) GetInstanceMetadataClient(ctx context.Context) (InstanceMetadata, error) {
c.mtx.RLock()
if c.instanceMetadata != nil {
defer c.mtx.RUnlock()
return c.instanceMetadata, nil
}
c.mtx.RUnlock()
return c.initInstanceMetadata(ctx)
}
// GetGCPGKEClient returns GKE client.
func (c *cloudClients) GetGCPGKEClient(ctx context.Context) (gcp.GKEClient, error) {
return c.gcpGKE.GetClient(ctx)
}
// GetGCPInstancesClient returns instances client.
func (c *cloudClients) GetGCPInstancesClient(ctx context.Context) (gcp.InstancesClient, error) {
return c.gcpInstances.GetClient(ctx)
}
// GetAzureCredential returns default Azure token credential chain.
func (c *cloudClients) GetAzureCredential() (azcore.TokenCredential, error) {
c.mtx.RLock()
if c.azureCredential != nil {
defer c.mtx.RUnlock()
return c.azureCredential, nil
}
c.mtx.RUnlock()
return c.initAzureCredential()
}
// GetAzureMySQLClient returns an AzureClient for MySQL for the given subscription.
func (c *cloudClients) GetAzureMySQLClient(subscription string) (azure.DBServersClient, error) {
c.mtx.RLock()
if client, ok := c.azureMySQLClients[subscription]; ok {
c.mtx.RUnlock()
return client, nil
}
c.mtx.RUnlock()
return c.initAzureMySQLClient(subscription)
}
// GetAzurePostgresClient returns an AzureClient for Postgres for the given subscription.
func (c *cloudClients) GetAzurePostgresClient(subscription string) (azure.DBServersClient, error) {
c.mtx.RLock()
if client, ok := c.azurePostgresClients[subscription]; ok {
c.mtx.RUnlock()
return client, nil
}
c.mtx.RUnlock()
return c.initAzurePostgresClient(subscription)
}
// GetAzureSubscriptionClient returns an Azure client for listing subscriptions.
func (c *cloudClients) GetAzureSubscriptionClient() (*azure.SubscriptionClient, error) {
c.mtx.RLock()
if c.azureSubscriptionsClient != nil {
defer c.mtx.RUnlock()
return c.azureSubscriptionsClient, nil
}
c.mtx.RUnlock()
return c.initAzureSubscriptionsClient()
}
// GetAzureRedisClient returns an Azure Redis client for the given subscription.
func (c *cloudClients) GetAzureRedisClient(subscription string) (azure.RedisClient, error) {
return c.azureRedisClients.Get(subscription, c.GetAzureCredential)
}
// GetAzureRedisEnterpriseClient returns an Azure Redis Enterprise client for the given subscription.
func (c *cloudClients) GetAzureRedisEnterpriseClient(subscription string) (azure.RedisEnterpriseClient, error) {
return c.azureRedisEnterpriseClients.Get(subscription, c.GetAzureCredential)
}
// GetAzureKubernetesClient returns an Azure client for listing AKS clusters.
func (c *cloudClients) GetAzureKubernetesClient(subscription string) (azure.AKSClient, error) {
c.mtx.RLock()
if client, ok := c.azureKubernetesClient[subscription]; ok {
c.mtx.RUnlock()
return client, nil
}
c.mtx.RUnlock()
return c.initAzureKubernetesClient(subscription)
}
// GetAzureVirtualMachinesClient returns an Azure Virtual Machines client for
// the given subscription.
func (c *cloudClients) GetAzureVirtualMachinesClient(subscription string) (azure.VirtualMachinesClient, error) {
return c.azureVirtualMachinesClients.Get(subscription, c.GetAzureCredential)
}
// GetAzureSQLServerClient returns an Azure client for listing SQL servers.
func (c *cloudClients) GetAzureSQLServerClient(subscription string) (azure.SQLServerClient, error) {
return c.azureSQLServerClients.Get(subscription, c.GetAzureCredential)
}
// GetAzureManagedSQLServerClient returns an Azure client for listing managed
// SQL servers.
func (c *cloudClients) GetAzureManagedSQLServerClient(subscription string) (azure.ManagedSQLServerClient, error) {
return c.azureManagedSQLServerClients.Get(subscription, c.GetAzureCredential)
}
// GetAzureMySQLFlexServersClient returns an Azure MySQL Flexible server client for listing MySQL Flexible servers.
func (c *cloudClients) GetAzureMySQLFlexServersClient(subscription string) (azure.MySQLFlexServersClient, error) {
return c.azureMySQLFlexServersClients.Get(subscription, c.GetAzureCredential)
}
// GetAzurePostgresFlexServersClient returns an Azure PostgreSQL Flexible server client for listing PostgreSQL Flexible servers.
func (c *cloudClients) GetAzurePostgresFlexServersClient(subscription string) (azure.PostgresFlexServersClient, error) {
return c.azurePostgresFlexServersClients.Get(subscription, c.GetAzureCredential)
}
// GetAzureRunCommandClient returns an Azure Run Command client for the given
// subscription.
func (c *cloudClients) GetAzureRunCommandClient(subscription string) (azure.RunCommandClient, error) {
return c.azureRunCommandClients.Get(subscription, c.GetAzureCredential)
}
// Close closes all initialized clients.
func (c *cloudClients) Close() (err error) {
c.mtx.Lock()
defer c.mtx.Unlock()
if c.gcpIAM != nil {
err = c.gcpIAM.Close()
c.gcpIAM = nil
}
return trace.Wrap(err)
}
// awsAmbientSessionProvider loads a new session using the environment variables.
// Describe in detail here: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html#specifying-credentials
func awsAmbientSessionProvider(ctx context.Context, region string) (*awssession.Session, error) {
awsSessionOptions := buildAWSSessionOptions(region, nil /* credentials */)
session, err := awssession.NewSessionWithOptions(awsSessionOptions)
return session, trace.Wrap(err)
}
// getAWSSessionForRegion returns AWS session for the specified region.
func (c *cloudClients) getAWSSessionForRegion(region string, opts awsAssumeRoleOpts) (*awssession.Session, error) {
if err := opts.checkAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
cacheKey := awsSessionCacheKey{
region: region,
integration: opts.integration,
}
return utils.FnCacheGet(context.Background(), c.awsSessionsCache, cacheKey, func(ctx context.Context) (*awssession.Session, error) {
if opts.credentialsSource == credentialsSourceIntegration {
if c.awsIntegrationSessionProviderFn == nil {
return nil, trace.BadParameter("missing aws integration session provider")
}
logrus.Debugf("Initializing AWS session for region %v with integration %q.", region, opts.integration)
session, err := c.awsIntegrationSessionProviderFn(ctx, region, opts.integration)
return session, trace.Wrap(err)
}
logrus.Debugf("Initializing AWS session for region %v using environment credentials.", region)
session, err := awsAmbientSessionProvider(ctx, region)
return session, trace.Wrap(err)
})
}
// getAWSSessionForRole returns AWS session for the specified region and role.
func (c *cloudClients) getAWSSessionForRole(ctx context.Context, region string, options awsAssumeRoleOpts) (*awssession.Session, error) {
if err := options.checkAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
cacheKey := awsSessionCacheKey{
region: region,
integration: options.integration,
roleARN: options.assumeRoleARN,
externalID: options.assumeRoleExternalID,
}
return utils.FnCacheGet(ctx, c.awsSessionsCache, cacheKey, func(ctx context.Context) (*awssession.Session, error) {
stsClient := sts.New(options.baseSession)
return newSessionWithRole(ctx, stsClient, region, options.assumeRoleARN, options.assumeRoleExternalID)
})
}
func (c *cloudClients) initGCPIAMClient(ctx context.Context) (*gcpcredentials.IamCredentialsClient, error) {
c.mtx.Lock()
defer c.mtx.Unlock()
if c.gcpIAM != nil { // If some other thread already got here first.
return c.gcpIAM, nil
}
logrus.Debug("Initializing GCP IAM client.")
gcpIAM, err := gcpcredentials.NewIamCredentialsClient(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
c.gcpIAM = gcpIAM
return gcpIAM, nil
}
func (c *cloudClients) initAzureCredential() (azcore.TokenCredential, error) {
c.mtx.Lock()
defer c.mtx.Unlock()
if c.azureCredential != nil { // If some other thread already got here first.
return c.azureCredential, nil
}
logrus.Debug("Initializing Azure default credential chain.")
// TODO(gavin): if/when we support AzureChina/AzureGovernment, we will need to specify the cloud in these options
options := &azidentity.DefaultAzureCredentialOptions{}
cred, err := azidentity.NewDefaultAzureCredential(options)
if err != nil {
return nil, trace.Wrap(err)
}
c.azureCredential = cred
return cred, nil
}
func (c *cloudClients) initAzureMySQLClient(subscription string) (azure.DBServersClient, error) {
cred, err := c.GetAzureCredential()
if err != nil {
return nil, trace.Wrap(err)
}
c.mtx.Lock()
defer c.mtx.Unlock()
if client, ok := c.azureMySQLClients[subscription]; ok { // If some other thread already got here first.
return client, nil
}
logrus.Debug("Initializing Azure MySQL servers client.")
// TODO(gavin): if/when we support AzureChina/AzureGovernment, we will need to specify the cloud in these options
options := &arm.ClientOptions{}
api, err := armmysql.NewServersClient(subscription, cred, options)
if err != nil {
return nil, trace.Wrap(err)
}
client := azure.NewMySQLServersClient(api)
c.azureMySQLClients[subscription] = client
return client, nil
}
func (c *cloudClients) initAzurePostgresClient(subscription string) (azure.DBServersClient, error) {
cred, err := c.GetAzureCredential()
if err != nil {
return nil, trace.Wrap(err)
}
c.mtx.Lock()
defer c.mtx.Unlock()
if client, ok := c.azurePostgresClients[subscription]; ok { // If some other thread already got here first.
return client, nil
}
logrus.Debug("Initializing Azure Postgres servers client.")
// TODO(gavin): if/when we support AzureChina/AzureGovernment, we will need to specify the cloud in these options
options := &arm.ClientOptions{}
api, err := armpostgresql.NewServersClient(subscription, cred, options)
if err != nil {
return nil, trace.Wrap(err)
}
client := azure.NewPostgresServerClient(api)
c.azurePostgresClients[subscription] = client
return client, nil
}
func (c *cloudClients) initAzureSubscriptionsClient() (*azure.SubscriptionClient, error) {
cred, err := c.GetAzureCredential()
if err != nil {
return nil, trace.Wrap(err)
}
c.mtx.Lock()
defer c.mtx.Unlock()
if c.azureSubscriptionsClient != nil { // If some other thread already got here first.
return c.azureSubscriptionsClient, nil
}
logrus.Debug("Initializing Azure subscriptions client.")
// TODO(gavin): if/when we support AzureChina/AzureGovernment,
// we will need to specify the cloud in these options
opts := &arm.ClientOptions{}
armClient, err := armsubscription.NewSubscriptionsClient(cred, opts)
if err != nil {
return nil, trace.Wrap(err)
}
client := azure.NewSubscriptionClient(armClient)
c.azureSubscriptionsClient = client
return client, nil
}
// initInstanceMetadata initializes the instance metadata client.
func (c *cloudClients) initInstanceMetadata(ctx context.Context) (InstanceMetadata, error) {
c.mtx.Lock()
defer c.mtx.Unlock()
if c.instanceMetadata != nil { // If some other thread already got here first.
return c.instanceMetadata, nil
}
logrus.Debug("Initializing instance metadata client.")
client, err := DiscoverInstanceMetadata(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
c.instanceMetadata = client
return client, nil
}
func (c *cloudClients) initAzureKubernetesClient(subscription string) (azure.AKSClient, error) {
cred, err := c.GetAzureCredential()
if err != nil {
return nil, trace.Wrap(err)
}
c.mtx.Lock()
defer c.mtx.Unlock()
if client, ok := c.azureKubernetesClient[subscription]; ok { // If some other thread already got here first.
return client, nil
}
logrus.Debug("Initializing Azure AKS client.")
// TODO(tigrato): if/when we support AzureChina/AzureGovernment, we will need to specify the cloud in these options
options := &arm.ClientOptions{}
api, err := armcontainerservice.NewManagedClustersClient(subscription, cred, options)
if err != nil {
return nil, trace.Wrap(err)
}
client := azure.NewAKSClustersClient(
api, func(options *azidentity.DefaultAzureCredentialOptions) (azure.GetToken, error) {
cc, err := azidentity.NewDefaultAzureCredential(options)
return cc, err
})
c.azureKubernetesClient[subscription] = client
return client, nil
}
// TestCloudClients implements Clients
var _ Clients = (*TestCloudClients)(nil)
// TestCloudClients are used in tests.
type TestCloudClients struct {
RDS rdsiface.RDSAPI
RDSPerRegion map[string]rdsiface.RDSAPI
Redshift redshiftiface.RedshiftAPI
RedshiftServerless redshiftserverlessiface.RedshiftServerlessAPI
ElastiCache elasticacheiface.ElastiCacheAPI
OpenSearch opensearchserviceiface.OpenSearchServiceAPI
MemoryDB memorydbiface.MemoryDBAPI
SecretsManager secretsmanageriface.SecretsManagerAPI
IAM iamiface.IAMAPI
STS stsiface.STSAPI
GCPSQL gcp.SQLAdminClient
GCPGKE gcp.GKEClient
GCPInstances gcp.InstancesClient
EC2 ec2iface.EC2API
SSM ssmiface.SSMAPI
InstanceMetadata InstanceMetadata
EKS eksiface.EKSAPI
AzureMySQL azure.DBServersClient
AzureMySQLPerSub map[string]azure.DBServersClient
AzurePostgres azure.DBServersClient
AzurePostgresPerSub map[string]azure.DBServersClient
AzureSubscriptionClient *azure.SubscriptionClient
AzureRedis azure.RedisClient
AzureRedisEnterprise azure.RedisEnterpriseClient
AzureAKSClientPerSub map[string]azure.AKSClient
AzureAKSClient azure.AKSClient
AzureVirtualMachines azure.VirtualMachinesClient
AzureSQLServer azure.SQLServerClient
AzureManagedSQLServer azure.ManagedSQLServerClient
AzureMySQLFlex azure.MySQLFlexServersClient
AzurePostgresFlex azure.PostgresFlexServersClient
AzureRunCommand azure.RunCommandClient
}
// GetAWSSession returns AWS session for the specified region, optionally
// assuming AWS IAM Roles.
func (c *TestCloudClients) GetAWSSession(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (*awssession.Session, error) {
var options awsAssumeRoleOpts
for _, opt := range opts {
opt(&options)
}
var err error
if options.baseSession == nil {
options.baseSession, err = c.getAWSSessionForRegion(region)
if err != nil {
return nil, trace.Wrap(err)
}
}
if options.assumeRoleARN == "" {
return options.baseSession, nil
}
return newSessionWithRole(ctx, c.STS, region, options.assumeRoleARN, options.assumeRoleExternalID)
}
// GetAWSSession returns AWS session for the specified region.
func (c *TestCloudClients) getAWSSessionForRegion(region string) (*awssession.Session, error) {
return awssession.NewSession(&aws.Config{
Credentials: credentials.NewCredentials(&credentials.StaticProvider{Value: credentials.Value{
AccessKeyID: "fakeClientKeyID",
SecretAccessKey: "fakeClientSecret",
}}),
Region: aws.String(region),
})
}
// GetAWSRDSClient returns AWS RDS client for the specified region.
func (c *TestCloudClients) GetAWSRDSClient(ctx context.Context, region string, opts ...AWSAssumeRoleOptionFn) (rdsiface.RDSAPI, error) {
_, err := c.GetAWSSession(ctx, region, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
if len(c.RDSPerRegion) != 0 {
return c.RDSPerRegion[region], nil