forked from openshift/cloud-credential-operator
/
actuator.go
1370 lines (1213 loc) · 46.4 KB
/
actuator.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 2018 The OpenShift Authors.
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 actuator
import (
"context"
"encoding/json"
"fmt"
"net/url"
"reflect"
log "github.com/sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/iam"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilrand "k8s.io/apimachinery/pkg/util/rand"
"sigs.k8s.io/controller-runtime/pkg/client"
minterv1 "github.com/openshift/cloud-credential-operator/pkg/apis/cloudcredential/v1"
ccaws "github.com/openshift/cloud-credential-operator/pkg/aws"
minteraws "github.com/openshift/cloud-credential-operator/pkg/aws"
"github.com/openshift/cloud-credential-operator/pkg/operator/constants"
actuatoriface "github.com/openshift/cloud-credential-operator/pkg/operator/credentialsrequest/actuator"
awsannotator "github.com/openshift/cloud-credential-operator/pkg/operator/secretannotator/aws"
"github.com/openshift/cloud-credential-operator/pkg/operator/utils"
awsutils "github.com/openshift/cloud-credential-operator/pkg/operator/utils/aws"
)
const (
roAWSCredsSecretNamespace = "openshift-cloud-credential-operator"
roAWSCredsSecret = "cloud-credential-operator-iam-ro-creds"
openshiftClusterIDKey = "openshiftClusterID"
clusterVersionObjectName = "version"
secretDataAccessKey = "aws_access_key_id"
secretDataSecretKey = "aws_secret_access_key"
)
var _ actuatoriface.Actuator = (*AWSActuator)(nil)
// AWSActuator implements the CredentialsRequest Actuator interface to create credentials in AWS.
type AWSActuator struct {
Client client.Client
Codec *minterv1.ProviderCodec
AWSClientBuilder func(accessKeyID, secretAccessKey []byte, c client.Client) (ccaws.Client, error)
Scheme *runtime.Scheme
}
// NewAWSActuator creates a new AWSActuator.
func NewAWSActuator(client client.Client, scheme *runtime.Scheme) (*AWSActuator, error) {
codec, err := minterv1.NewCodec()
if err != nil {
log.WithError(err).Error("error creating AWS codec")
return nil, fmt.Errorf("error creating AWS codec: %v", err)
}
return &AWSActuator{
Codec: codec,
Client: client,
AWSClientBuilder: awsutils.ClientBuilder,
Scheme: scheme,
}, nil
}
func DecodeProviderStatus(codec *minterv1.ProviderCodec, cr *minterv1.CredentialsRequest) (*minterv1.AWSProviderStatus, error) {
awsStatus := minterv1.AWSProviderStatus{}
var err error
if cr.Status.ProviderStatus == nil {
return &awsStatus, nil
}
err = codec.DecodeProviderStatus(cr.Status.ProviderStatus, &awsStatus)
if err != nil {
return nil, fmt.Errorf("error decoding v1 provider status: %v", err)
}
return &awsStatus, nil
}
func DecodeProviderSpec(codec *minterv1.ProviderCodec, cr *minterv1.CredentialsRequest) (*minterv1.AWSProviderSpec, error) {
if cr.Spec.ProviderSpec != nil {
awsSpec := minterv1.AWSProviderSpec{}
err := codec.DecodeProviderSpec(cr.Spec.ProviderSpec, &awsSpec)
if err != nil {
return nil, fmt.Errorf("error decoding provider v1 spec: %v", err)
}
return &awsSpec, nil
}
return nil, fmt.Errorf("no providerSpec defined")
}
// Checks if the credentials currently exist.
//
// To do this we will check if the target secret exists. This call is only used to determine
// if we're doing a Create or an Update, but in the context of this acutator it makes no
// difference. As such we will not check if the user exists in AWS and is correctly configured
// as this will all be handled in both Create and Update.
func (a *AWSActuator) Exists(ctx context.Context, cr *minterv1.CredentialsRequest) (bool, error) {
logger := a.getLogger(cr)
logger.Debug("running Exists")
var err error
if isAWS, err := isAWSCredentials(cr.Spec.ProviderSpec); !isAWS {
return false, err
}
existingSecret := &corev1.Secret{}
err = a.Client.Get(context.TODO(), types.NamespacedName{Namespace: cr.Spec.SecretRef.Namespace, Name: cr.Spec.SecretRef.Name}, existingSecret)
if err != nil {
if errors.IsNotFound(err) {
logger.Debug("target secret does not exist")
return false, nil
}
return false, err
}
logger.Debug("target secret exists")
return true, nil
}
// needsUpdate will return whether the current credentials satisfy what's being requested
// in the CredentialsRequest
func (a *AWSActuator) needsUpdate(ctx context.Context, cr *minterv1.CredentialsRequest) (bool, error) {
logger := a.getLogger(cr)
// If the secret simply doesn't exist, we definitely need an update
exists, err := a.Exists(ctx, cr)
if err != nil {
return true, err
}
if !exists {
return true, nil
}
// Various checks for the kinds of reasons that would trigger a needed update
_, existingAccessKey, existingSecretKey, existingCredentialsKey := a.loadExistingSecret(cr)
awsClient, err := a.AWSClientBuilder([]byte(existingAccessKey), []byte(existingSecretKey), a.Client)
if err != nil {
return true, err
}
// Make sure we update old Secrets that don't have the new "credentials" field
if existingCredentialsKey == "" || existingCredentialsKey != string(generateAWSCredentialsConfig(existingAccessKey, existingSecretKey)) {
logger.Infof("Secret %s key needs updating, will update Secret contents", constants.AWSSecretDataCredentialsKey)
return true, nil
}
awsSpec, err := DecodeProviderSpec(a.Codec, cr)
if err != nil {
return true, err
}
awsStatus, err := DecodeProviderStatus(a.Codec, cr)
if err != nil {
return true, fmt.Errorf("unable to decode ProviderStatus: %v", err)
}
// Minted-user-specific checks
if awsStatus.User != "" {
readAWSClient, err := a.buildReadAWSClient(cr)
if err != nil {
log.WithError(err).Error("error creating read-only AWS client")
return true, fmt.Errorf("unable to check whether AWS user is properly tagged")
}
// If AWS user defined (ie minted creds instead of passthrough) check whether user is tagged
user, err := readAWSClient.GetUser(&iam.GetUserInput{
UserName: aws.String(awsStatus.User),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case iam.ErrCodeNoSuchEntityException:
// Current user does not exist, we unset the user in the status and create a new one
logger.Errorf("user %s does not exist, creating a new user", awsStatus.User)
awsStatus.User = ""
return true, nil
default:
return true, formatAWSErr(aerr)
}
}
logger.WithError(err).Errorf("unknown error getting user: %s", user)
return true, fmt.Errorf("unable to read info for username %v: %v", user, err)
}
clusterUUID, err := a.loadClusterUUID(logger)
if err != nil {
return true, err
}
infraName, err := utils.LoadInfrastructureName(a.Client, logger)
if err != nil {
return true, err
}
if !userHasExpectedTags(logger, user.User, infraName, string(clusterUUID)) {
return true, nil
}
// Does the access key in the secret still exist?
logger.Debug("NeedsUpdate ListAccessKeys")
allUserKeys, err := readAWSClient.ListAccessKeys(&iam.ListAccessKeysInput{UserName: aws.String(awsStatus.User)})
if err != nil {
logger.WithError(err).Error("error listing all access keys for user")
return false, err
}
accessKeyExists, err := a.accessKeyExists(logger, allUserKeys, existingAccessKey)
if err != nil {
logger.WithError(err).Error("error querying whether access key still valid")
}
if !accessKeyExists {
// then we need an update
return true, nil
}
// Check whether the current policy attached to the creds match what is being requested
desiredUserPolicy, err := a.getDesiredUserPolicy(awsSpec.StatementEntries, *user.User.Arn)
if err != nil {
return false, err
}
policyEqual, err := a.awsPolicyEqualsDesiredPolicy(desiredUserPolicy, awsSpec, awsStatus, user.User, readAWSClient, logger)
if err != nil {
return true, err
}
if !policyEqual {
return true, nil
}
} else {
// for passthrough creds, just see if root cloud creds have not changed and
// we have the permissions requested in the credentials request
// but for the case where the operator mode is non-default, then we will avoid performing any
// policy simulations and assume that the passthrough creds must be good enough
credentialsRootSecret, err := a.GetCredentialsRootSecret(ctx, cr)
if err != nil {
log.WithError(err).Debug("error retrieving cloud credentials secret")
return false, err
}
// If the cloud credentials secret has been updated in passthrough mode, we need an update
if credentialsRootSecret != nil && credentialsRootSecret.ResourceVersion != cr.Status.LastSyncCloudCredsSecretResourceVersion {
logger.Debug("root cloud creds have changed, update is needed")
return true, nil
}
mode, _, err := utils.GetOperatorConfiguration(a.Client, logger)
if err != nil {
return true, err
}
if mode == operatorv1.CloudCredentialsModePassthrough {
logger.Debug("will not perform permissions simulation because operator in mode %q", mode)
} else {
region, err := awsutils.LoadInfrastructureRegion(a.Client, logger)
if err != nil {
return true, err
}
simParams := &ccaws.SimulateParams{
Region: region,
}
goodEnough, err := ccaws.CheckPermissionsAgainstStatementList(awsClient, awsSpec.StatementEntries, simParams, logger)
if err != nil {
return true, fmt.Errorf("error validating whether current creds are good enough: %v", err)
}
if !goodEnough {
return true, nil
}
}
}
// If we've made it this far, then there are no updates needed
return false, nil
}
// Create the credentials.
func (a *AWSActuator) Create(ctx context.Context, cr *minterv1.CredentialsRequest) error {
return a.sync(ctx, cr)
}
// Update the credentials to the provided definition.
func (a *AWSActuator) Update(ctx context.Context, cr *minterv1.CredentialsRequest) error {
return a.sync(ctx, cr)
}
func (a *AWSActuator) sync(ctx context.Context, cr *minterv1.CredentialsRequest) error {
if isAWS, err := isAWSCredentials(cr.Spec.ProviderSpec); !isAWS {
return err
}
logger := a.getLogger(cr)
logger.Debug("running sync")
// Should we update anything
needsUpdate, err := a.needsUpdate(ctx, cr)
if err != nil {
logger.WithError(err).Error("error determining whether a credentials update is needed")
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: "error determining whether a credentials update is needed",
}
}
if !needsUpdate {
logger.Debug("credentials already up to date")
return nil
}
mode, _, err := utils.GetOperatorConfiguration(a.Client, logger)
if mode == utils.CloudCredentialsModeToken {
logger.Info("actuator Token mode making secret")
if cr.Spec.CloudTokenString != "" {
err = a.createSecret(cr.Spec.CloudTokenString, cr.Spec.CloudTokenPath, cr.Spec.SecretRef.Name, cr.Spec.SecretRef.Namespace, logger)
}
if err != nil {
return err
}
} else {
credentialsRootSecret, err := a.GetCredentialsRootSecret(ctx, cr)
if err != nil {
logger.WithError(err).Error("issue with cloud credentials secret")
return err
}
switch credentialsRootSecret.Annotations[constants.AnnotationKey] {
case constants.InsufficientAnnotation:
msg := "cloud credentials insufficient to satisfy credentials request"
logger.Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.InsufficientCloudCredentials,
Message: msg,
}
case constants.PassthroughAnnotation:
logger.Debugf("provisioning with passthrough")
err := a.syncPassthrough(ctx, cr, credentialsRootSecret, logger)
if err != nil {
return err
}
case constants.MintAnnotation:
logger.Debugf("provisioning with cred minting")
err := a.syncMint(ctx, cr, logger)
if err != nil {
msg := "error syncing creds in mint-mode"
logger.WithError(err).Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: fmt.Sprintf("%v: %v", msg, err),
}
}
default:
msg := fmt.Sprintf("unexpected value or missing %s annotation on admin credentials Secret", constants.AnnotationKey)
logger.Info(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: msg,
}
}
}
return nil
}
// createSecret makes a time-based token available in a Secret in the namespace of an operator that
// has supplied the following in the CredentialsRequest:
// a non-nil spec.CloudTokenString
// a path to the JWT token: spec.cloudTokenPath
// a spec.SecretRef.Name
// a cr.Spec.SecretRef.Namespace
func (a *AWSActuator) createSecret(cloudTokenString string, cloudTokenPath string, secretRef string,
secretRefNamespace string, log log.FieldLogger) error {
log.Infof("creating secret")
credsTemplate :=
`sts_regional_endpoints = regional
role_arn = %s
web_identity_token_file = %s`
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretRef,
Namespace: secretRefNamespace,
},
StringData: map[string]string{
"credentials": fmt.Sprintf(credsTemplate, cloudTokenString, cloudTokenPath),
},
Type: corev1.SecretTypeOpaque,
}
err := a.Client.Create(context.TODO(), secret)
if err != nil {
log.Errorf("error creating secret")
return err
}
log.Info("secret created successfully")
return nil
}
func (a *AWSActuator) syncPassthrough(ctx context.Context, cr *minterv1.CredentialsRequest, cloudCredsSecret *corev1.Secret, logger log.FieldLogger) error {
existingSecret, _, _, _ := a.loadExistingSecret(cr)
accessKeyID := string(cloudCredsSecret.Data[awsannotator.AwsAccessKeyName])
secretAccessKey := string(cloudCredsSecret.Data[awsannotator.AwsSecretAccessKeyName])
mode, _, err := utils.GetOperatorConfiguration(a.Client, logger)
if err != nil {
msg := "error getting operator configuration"
logger.WithError(err).Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: fmt.Sprintf("%v: %v", msg, err),
}
}
if mode == operatorv1.CloudCredentialsModePassthrough {
logger.Debug("will not perform permissions simulation because operator in mode %q", mode)
} else {
region, err := awsutils.LoadInfrastructureRegion(a.Client, logger)
if err != nil {
msg := "error reading region from Infrastructure CR"
logger.WithError(err).Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: fmt.Sprintf("%v: %v", msg, err),
}
}
simParams := &ccaws.SimulateParams{
Region: region,
}
// build client with root secret and verify that the creds are good enough to pass through
awsClient, err := a.AWSClientBuilder([]byte(accessKeyID), []byte(secretAccessKey), a.Client)
if err != nil {
msg := "error building AWS client"
logger.WithError(err).Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: fmt.Sprintf("%v: %v", msg, err),
}
}
awsSpec, err := DecodeProviderSpec(a.Codec, cr)
if err != nil {
msg := "error decoding AWS ProviderSpec"
logger.WithError(err).Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: fmt.Sprintf("%v: %v", msg, err),
}
}
goodEnough, err := ccaws.CheckPermissionsAgainstStatementList(awsClient, awsSpec.StatementEntries, simParams, logger)
if err != nil {
msg := "error validating whether root creds are good enough"
logger.WithError(err).Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: fmt.Sprintf("%v: %v", msg, err),
}
}
if !goodEnough {
msg := "root creds are not sufficient"
logger.Info(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: fmt.Sprintf("%v", msg),
}
}
}
// userPolicy param empty because in passthrough mode this doesn't really have any meaning
err = a.syncAccessKeySecret(cr, accessKeyID, secretAccessKey, existingSecret, "", logger)
if err != nil {
msg := "error creating/updating secret"
logger.WithError(err).Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: fmt.Sprintf("%v: %v", msg, err),
}
}
return nil
}
// syncMint handles both create and update idempotently.
func (a *AWSActuator) syncMint(ctx context.Context, cr *minterv1.CredentialsRequest, logger log.FieldLogger) error {
var err error
awsSpec, err := DecodeProviderSpec(a.Codec, cr)
if err != nil {
return err
}
awsStatus, err := DecodeProviderStatus(a.Codec, cr)
if err != nil {
return err
}
infraName, err := utils.LoadInfrastructureName(a.Client, logger)
if err != nil {
return err
}
// Generate a randomized User for the credentials:
// TODO: check if the generated name is free
if awsStatus.User == "" {
username, err := generateUserName(infraName, cr.Name)
if err != nil {
return err
}
awsStatus.User = username
awsStatus.Policy = getPolicyName(username)
logger.WithField("user", awsStatus.User).Debug("generated random name for AWS user and policy")
err = a.updateProviderStatus(ctx, logger, cr, awsStatus)
if err != nil {
return err
}
}
if awsStatus.Policy == "" && awsStatus.User != "" {
awsStatus.Policy = getPolicyName(awsStatus.User)
err = a.updateProviderStatus(ctx, logger, cr, awsStatus)
if err != nil {
return err
}
}
rootAWSClient, err := a.buildRootAWSClient(cr)
if err != nil {
logger.WithError(err).Warn("error building root AWS client, will error if one must be used")
}
readAWSClient, err := a.buildReadAWSClient(cr)
if err != nil {
logger.WithError(err).Error("error building read-only AWS client")
return err
}
// Check if the user already exists:
var userOut *iam.User
getUserOut, err := readAWSClient.GetUser(&iam.GetUserInput{UserName: aws.String(awsStatus.User)})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case iam.ErrCodeNoSuchEntityException:
logger.WithField("userName", awsStatus.User).Debug("user does not exist, creating")
if rootAWSClient == nil {
return fmt.Errorf("no root AWS client available, cred secret may not exist: %s/%s", constants.CloudCredSecretNamespace, constants.AWSCloudCredSecretName)
}
createOut, err := a.createUser(logger, rootAWSClient, awsStatus.User)
if err != nil {
return err
}
logger.WithField("userName", awsStatus.User).Info("user created successfully")
userOut = createOut.User
default:
return formatAWSErr(aerr)
}
} else {
return fmt.Errorf("unknown error getting user from AWS: %v", err)
}
} else {
logger.WithField("userName", awsStatus.User).Info("user exists")
userOut = getUserOut.User
}
clusterUUID, err := a.loadClusterUUID(logger)
if err != nil {
return err
}
// Check if the user has the expected tags:
if !userHasExpectedTags(logger, userOut, infraName, string(clusterUUID)) {
if rootAWSClient == nil {
return fmt.Errorf("no root AWS client available, cred secret may not exist: %s/%s", constants.CloudCredSecretNamespace, constants.AWSCloudCredSecretName)
}
err = a.tagUser(logger, rootAWSClient, awsStatus.User, infraName, string(clusterUUID))
if err != nil {
return err
}
}
// TODO: check if user policy needs to be set? user generation and last set time.
desiredUserPolicy, err := a.getDesiredUserPolicy(awsSpec.StatementEntries, *userOut.Arn)
if err != nil {
return err
}
policyEqual, err := a.awsPolicyEqualsDesiredPolicy(desiredUserPolicy, awsSpec, awsStatus, userOut, readAWSClient, logger)
if !policyEqual {
if rootAWSClient == nil {
return fmt.Errorf("no root AWS client available, cred secret may not exist: %s/%s", constants.CloudCredSecretNamespace, constants.AWSCloudCredSecretName)
}
err = a.setUserPolicy(logger, rootAWSClient, awsStatus.User, awsStatus.Policy, desiredUserPolicy)
if err != nil {
return err
}
logger.Info("successfully set user policy")
}
logger.Debug("sync ListAccessKeys")
allUserKeys, err := readAWSClient.ListAccessKeys(&iam.ListAccessKeysInput{UserName: aws.String(awsStatus.User)})
if err != nil {
logger.WithError(err).Error("error listing all access keys for user")
return err
}
existingSecret, existingAccessKeyID, _, _ := a.loadExistingSecret(cr)
var accessKey *iam.AccessKey
// TODO: also check if the access key ID on the request is still valid in AWS
accessKeyExists, err := a.accessKeyExists(logger, allUserKeys, existingAccessKeyID)
if err != nil {
return err
}
logger.WithField("accessKeyID", existingAccessKeyID).Debugf("access key exists? %v", accessKeyExists)
if existingSecret != nil && existingSecret.Name != "" {
_, ok := existingSecret.Annotations[minterv1.AnnotationAWSPolicyLastApplied]
if !ok {
logger.Warnf("target secret missing policy annotation: %s", minterv1.AnnotationAWSPolicyLastApplied)
}
}
genNewAccessKey := existingSecret == nil || existingSecret.Name == "" || existingAccessKeyID == "" || !accessKeyExists
if genNewAccessKey {
logger.Info("generating new AWS access key")
// Users are allowed a max of two keys, if we decided we need to generate one,
// we should cleanup all pre-existing access keys. This will allow deleting the
// secret in Kubernetes to revoke old credentials and create new.
if rootAWSClient == nil {
return fmt.Errorf("no root AWS client available, cred secret may not exist: %s/%s", constants.CloudCredSecretNamespace, constants.AWSCloudCredSecretName)
}
err := a.deleteAllAccessKeys(logger, rootAWSClient, awsStatus.User, allUserKeys)
if err != nil {
return err
}
accessKey, err = a.createAccessKey(logger, rootAWSClient, awsStatus.User)
if err != nil {
logger.WithError(err).Error("error creating AWS access key")
return err
}
}
accessKeyString := ""
secretAccessKeyString := ""
if accessKey != nil {
accessKeyString = *accessKey.AccessKeyId
secretAccessKeyString = *accessKey.SecretAccessKey
}
err = a.syncAccessKeySecret(cr, accessKeyString, secretAccessKeyString, existingSecret, desiredUserPolicy, logger)
if err != nil {
log.WithError(err).Error("error saving access key to secret")
return err
}
return nil
}
func (a *AWSActuator) awsPolicyEqualsDesiredPolicy(desiredUserPolicy string, awsSpec *minterv1.AWSProviderSpec, awsStatus *minterv1.AWSProviderStatus, awsUser *iam.User, readAWSClient ccaws.Client, logger log.FieldLogger) (bool, error) {
currentUserPolicy, err := a.getCurrentUserPolicy(logger, readAWSClient, awsStatus.User, awsStatus.Policy)
if err != nil {
return false, err
}
logger.Debugf("desired user policy: %s", desiredUserPolicy)
logger.Debugf("current user policy: %s", currentUserPolicy)
if currentUserPolicy != desiredUserPolicy {
logger.Debug("policy differences detected")
return false, nil
}
logger.Debug("no changes to user policy")
return true, nil
}
func userHasExpectedTags(logger log.FieldLogger, user *iam.User, infraName, clusterUUID string) bool {
// Check if the user has the expected tags:
if user == nil {
return false
}
if infraName != "" {
clusterTag := fmt.Sprintf("kubernetes.io/cluster/%s", infraName)
if !userHasTag(user, clusterTag, "owned") {
log.Warnf("user missing tag: %s=%s", clusterTag, "owned")
return false
}
} else {
logger.Warn("Infrastructure 'cluster' has no status.infrastructureName set. (likely beta3 cluster)")
// This is a legacy tag being kept for compatability with beta3, which would not have
// had any infrastructure name set. Deprovision code still searches for anything with this
// tag, so if no infra name is set we skip that tag and rely on this one for cleanup.
if !userHasTag(user, openshiftClusterIDKey, clusterUUID) {
log.Warnf("user missing tag: %s=%s", openshiftClusterIDKey, clusterUUID)
return false
}
}
return true
}
func (a *AWSActuator) updateProviderStatus(ctx context.Context, logger log.FieldLogger, cr *minterv1.CredentialsRequest, awsStatus *minterv1.AWSProviderStatus) error {
var err error
cr.Status.ProviderStatus, err = a.Codec.EncodeProviderStatus(awsStatus)
if err != nil {
logger.WithError(err).Error("error encoding provider status")
return err
}
if cr.Status.Conditions == nil {
cr.Status.Conditions = []minterv1.CredentialsRequestCondition{}
}
err = a.Client.Status().Update(ctx, cr)
if err != nil {
logger.WithError(err).Error("error updating credentials request status")
return err
}
return nil
}
// Delete the credentials. If no error is returned, it is assumed that all dependent resources have been cleaned up.
func (a *AWSActuator) Delete(ctx context.Context, cr *minterv1.CredentialsRequest) error {
if isAWS, err := isAWSCredentials(cr.Spec.ProviderSpec); !isAWS {
return err
}
logger := a.getLogger(cr)
logger.Debug("running Delete")
var err error
awsStatus, err := DecodeProviderStatus(a.Codec, cr)
if err != nil {
return err
}
if awsStatus.User == "" {
logger.Warn("no user name set on credentials being deleted, most likely were never provisioned or using passthrough creds")
return nil
}
logger = logger.WithField("userName", awsStatus.User)
logger.Info("deleting credential from AWS")
awsClient, err := a.buildRootAWSClient(cr)
if err != nil {
return err
}
_, err = awsClient.DeleteUserPolicy(&iam.DeleteUserPolicyInput{
UserName: aws.String(awsStatus.User),
PolicyName: aws.String(awsStatus.Policy),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case iam.ErrCodeNoSuchEntityException:
logger.Warn("user policy does not exist, ignoring error")
default:
return formatAWSErr(aerr)
}
} else {
return fmt.Errorf("unknown error deleting user policy from AWS: %v", err)
}
}
logger.Info("user policy deleted")
logger.Debug("Delete ListAccessKeys")
allUserKeys, err := awsClient.ListAccessKeys(&iam.ListAccessKeysInput{UserName: aws.String(awsStatus.User)})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case iam.ErrCodeNoSuchEntityException:
logger.Warn("error listing access keys, user does not exist, returning success")
return nil
default:
logger.WithError(err).Error("error listing all access keys for user")
return formatAWSErr(aerr)
}
}
logger.WithError(err).Error("error listing all access keys for user")
return err
}
err = a.deleteAllAccessKeys(logger, awsClient, awsStatus.User, allUserKeys)
if err != nil {
return err
}
_, err = awsClient.DeleteUser(&iam.DeleteUserInput{
UserName: aws.String(awsStatus.User),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case iam.ErrCodeNoSuchEntityException:
logger.Warn("user does not exist, returning success")
default:
return formatAWSErr(aerr)
}
} else {
return fmt.Errorf("unknown error deleting user from AWS: %v", err)
}
}
logger.Info("user deleted")
return nil
}
func (a *AWSActuator) loadExistingSecret(cr *minterv1.CredentialsRequest) (*corev1.Secret, string, string, string) {
logger := a.getLogger(cr)
var existingAccessKeyID string
var existingSecretAccessKey string
var existingCredentialsKey string
// Check if the credentials secret exists, if not we need to inform the syncer to generate a new one:
existingSecret := &corev1.Secret{}
err := a.Client.Get(context.TODO(), types.NamespacedName{Namespace: cr.Spec.SecretRef.Namespace, Name: cr.Spec.SecretRef.Name}, existingSecret)
if err != nil {
if errors.IsNotFound(err) {
logger.Debug("secret does not exist")
}
} else {
keyBytes, ok := existingSecret.Data[secretDataAccessKey]
if !ok {
// Warn, but this will trigger generation of a new key and updating the secret.
logger.Warningf("secret did not have expected key: %s, will be regenerated", secretDataAccessKey)
} else {
decoded := string(keyBytes)
existingAccessKeyID = string(decoded)
logger.WithField("accessKeyID", existingAccessKeyID).Debug("found access key ID in target secret")
}
secretBytes, ok := existingSecret.Data[secretDataSecretKey]
if !ok {
logger.Warningf("secret did not have expected key: %s", secretDataSecretKey)
} else {
existingSecretAccessKey = string(secretBytes)
}
credentialsKey, ok := existingSecret.Data[constants.AWSSecretDataCredentialsKey]
if !ok {
logger.Warningf("secret did not have expected key: %s, will be updated", constants.AWSSecretDataCredentialsKey)
} else {
existingCredentialsKey = string(credentialsKey)
}
}
return existingSecret, existingAccessKeyID, existingSecretAccessKey, existingCredentialsKey
}
func (a *AWSActuator) tagUser(logger log.FieldLogger, awsClient minteraws.Client, username, infraName, clusterUUID string) error {
logger.WithField("infraName", infraName).Info("tagging user with infrastructure name")
tags := []*iam.Tag{}
if infraName != "" {
tags = append(tags, &iam.Tag{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", infraName)),
Value: aws.String("owned"),
})
} else {
tags = append(tags, &iam.Tag{
Key: aws.String(openshiftClusterIDKey),
Value: aws.String(clusterUUID),
})
}
_, err := awsClient.TagUser(&iam.TagUserInput{
UserName: aws.String(username),
Tags: tags,
})
if err != nil {
logger.WithError(err).Error("unable to tag user")
return err
}
return nil
}
// buildRootAWSClient will return an AWS client using the "root" AWS creds which are expected to
// live in kube-system/aws-creds.
func (a *AWSActuator) buildRootAWSClient(cr *minterv1.CredentialsRequest) (minteraws.Client, error) {
logger := a.getLogger(cr).WithField("secret", fmt.Sprintf("%s/%s", constants.CloudCredSecretNamespace, constants.AWSCloudCredSecretName))
logger.Debug("loading AWS credentials from secret")
// TODO: Running in a 4.0 cluster we expect this secret to exist. When we run in a Hive
// cluster, we need to load different secrets for each cluster.
accessKeyID, secretAccessKey, err := utils.LoadCredsFromSecret(a.Client, constants.CloudCredSecretNamespace, constants.AWSCloudCredSecretName)
if err != nil {
return nil, err
}
logger.Debug("creating root AWS client")
return a.AWSClientBuilder(accessKeyID, secretAccessKey, a.Client)
}
// buildReadAWSClient will return an AWS client using the the scaled down read only AWS creds
// for cred minter, which are expected to live in openshift-cloud-credential-operator/cloud-credential-operator-iam-ro-creds.
// These creds would normally be created by cred minter itself, via a CredentialsRequest created
// by the cred minter operator.
//
// If these are not available but root creds are, we will use the root creds instead.
// This allows us to create the read creds initially.
func (a *AWSActuator) buildReadAWSClient(cr *minterv1.CredentialsRequest) (minteraws.Client, error) {
logger := a.getLogger(cr).WithField("secret", fmt.Sprintf("%s/%s", roAWSCredsSecretNamespace, roAWSCredsSecret))
logger.Debug("loading AWS credentials from secret")
var accessKeyID, secretAccessKey []byte
var err error
// TODO: Running in a 4.0 cluster we expect this secret to exist. When we run in a Hive
// cluster, we need to load different secrets for each cluster.
accessKeyID, secretAccessKey, err = utils.LoadCredsFromSecret(a.Client, roAWSCredsSecretNamespace, roAWSCredsSecret)
if err != nil {
if errors.IsNotFound(err) {
logger.Warn("read-only creds not found, using root creds client")
return a.buildRootAWSClient(cr)
}
logger.WithError(err).Error("unexpected error while trying to load in read-only creds Secret")
return nil, err
}
logger.Debug("creating read AWS client")
client, err := a.AWSClientBuilder(accessKeyID, secretAccessKey, a.Client)
if err != nil {
return nil, err
}
// Test if the read-only client is working, if any error here we will fall back to using
// the root client.
// and if our RO user is not yet live, we should just fall back to using the root user
// if possible.
awsStatus, err := DecodeProviderStatus(a.Codec, cr)
if err != nil {
return nil, err
}
_, err = client.GetUser(&iam.GetUserInput{UserName: aws.String(awsStatus.User)})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case "InvalidClientTokenId":
logger.Warn("InvalidClientTokenId for read-only AWS account, likely a propagation delay, falling back to root AWS client")
return a.buildRootAWSClient(cr)
}
// Any other error we just let following code sort out.
}
}
return client, nil
}
func (a *AWSActuator) getLogger(cr *minterv1.CredentialsRequest) log.FieldLogger {
return log.WithFields(log.Fields{
"actuator": "aws",
"cr": fmt.Sprintf("%s/%s", cr.Namespace, cr.Name),
})
}
func (a *AWSActuator) syncAccessKeySecret(cr *minterv1.CredentialsRequest, accessKeyID, secretAccessKey string, existingSecret *corev1.Secret, userPolicy string, logger log.FieldLogger) error {
sLog := logger.WithFields(log.Fields{
"targetSecret": fmt.Sprintf("%s/%s", cr.Spec.SecretRef.Namespace, cr.Spec.SecretRef.Name),
"cr": fmt.Sprintf("%s/%s", cr.Namespace, cr.Name),
})
if existingSecret == nil || existingSecret.Name == "" {
if accessKeyID == "" || secretAccessKey == "" {
msg := "new access key secret needed but no key data provided"
sLog.Error(msg)
return &actuatoriface.ActuatorError{
ErrReason: minterv1.CredentialsProvisionFailure,
Message: msg,
}
}
sLog.Info("creating secret")
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: cr.Spec.SecretRef.Name,
Namespace: cr.Spec.SecretRef.Namespace,
Annotations: map[string]string{
minterv1.AnnotationCredentialsRequest: fmt.Sprintf("%s/%s", cr.Namespace, cr.Name),
minterv1.AnnotationAWSPolicyLastApplied: userPolicy,
},
},
Data: map[string][]byte{
secretDataAccessKey: []byte(accessKeyID),
secretDataSecretKey: []byte(secretAccessKey),
constants.AWSSecretDataCredentialsKey: generateAWSCredentialsConfig(accessKeyID, secretAccessKey),