-
Notifications
You must be signed in to change notification settings - Fork 139
/
create_identity_provider.go
797 lines (731 loc) · 32 KB
/
create_identity_provider.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
package aws
import (
"bytes"
"crypto/sha1"
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
awssdk "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/service/cloudfront"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/pkg/errors"
"github.com/spf13/cobra"
jose "gopkg.in/square/go-jose.v2"
"github.com/openshift/cloud-credential-operator/pkg/aws"
"github.com/openshift/cloud-credential-operator/pkg/cmd/provisioning"
)
var (
// CreateIdentityProviderOpts captures the options that affect creation of the identity provider
CreateIdentityProviderOpts = options{
Name: "",
Region: "",
PublicKeyPath: "",
TargetDir: "",
}
// S3 bucket template (usable with aws CLI --cli-input-json param)
oidcBucketTemplateWithLocation = `{
"ACL": "private",
"Bucket": "%s",
"CreateBucketConfiguration": {
"LocationConstraint": "%s"
}
}`
// 'us-east-1' is the default region, and AWS returns an error if you try to set it
oidcBucketTemplateWithoutLocation = `{
"ACL": "private",
"Bucket": "%s"
}`
// Block public access to S3 bucket template (usable with aws CLI --cli-input-json param)
blockPublicAccessToOidcBucketTemplate = `{
"Bucket": "%s",
"PublicAccessBlockConfiguration": {
"BlockPublicAcls": true,
"IgnorePublicAcls": true,
"BlockPublicPolicy": true,
"RestrictPublicBuckets": true
},
}`
// iam identity provider with "openshift" and "sts.amazonaws.com" as static audiences
iamIdentityProviderTemplate = `{
"Url": "%s",
"ClientIDList": [
"openshift",
"sts.amazonaws.com"
],
"ThumbprintList": [
"%s"
]
}
`
// oidcBucketTemplateAllowingOAIAccess is the S3 bucket policy allowing access to CloudFront Origin Access Identity
oidcBucketTemplateAllowingOAIAccess = `{
"Version": "2008-10-17",
"Id": "PolicyForCloudFrontPrivateContent",
"Statement": [
{
"Sid": "1",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity %s"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::%s/*"
}
]
}`
// cloudFrontOriginAccessIdentityTemplate is the template for CloudFront Origin Access Identity (usable with aws CLI --cli-input-json param)
cloudFrontOriginAccessIdentityTemplate = `{
"CloudFrontOriginAccessIdentityConfig":{
"CallerReference":"%s",
"Comment":"%s"
}
}`
// putBucketPolicyToAllowOriginAccessIdentityTemplate is a template for making OIDC S3 bucket accessible by
// CloudFront Origin Access Identity (usable with aws CLI --cli-input-json param)
putBucketPolicyToAllowOriginAccessIdentityTemplate = `{
"Bucket": "%s",
"Policy": "{\"Version\":\"2008-10-17\",\"Id\":\"PolicyForCloudFrontPrivateContent\",\"Statement\":[{\"Sid\":\"1\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::cloudfront:user\/CloudFront Origin Access Identity <enter_cloudfront_origin_access_identity_here>\"},\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::%s\/*\"}]}"
}`
// cloudFrontDistributionWithTagsTemplate is a template for creating CloudFront Distribution with tags
// (usable with aws CLI --cli-input-json param)
cloudFrontDistributionWithTagsTemplate = `{
"DistributionConfigWithTags":{
"DistributionConfig":{
"CallerReference":"%s",
"Aliases":{
"Quantity":0
},
"Origins":{
"Quantity":1,
"Items":[
{
"Id":"%s.s3.%s.%s",
"DomainName":"%s.s3.%s.%s",
"OriginPath":"",
"CustomHeaders":{
"Quantity":0
},
"S3OriginConfig":{
"OriginAccessIdentity":"origin-access-identity/cloudfront/<enter_cloudfront_origin_access_identity_here>"
},
"ConnectionAttempts":3,
"ConnectionTimeout":10,
"OriginShield":{
"Enabled":false
}
}
]
},
"DefaultCacheBehavior":{
"TargetOriginId":"%s.s3.%s.%s",
"TrustedSigners":{
"Enabled":false,
"Quantity":0
},
"TrustedKeyGroups":{
"Enabled":false,
"Quantity":0
},
"ViewerProtocolPolicy":"https-only",
"AllowedMethods":{
"Quantity":2,
"Items":[
"HEAD",
"GET"
],
"CachedMethods":{
"Quantity":2,
"Items":[
"HEAD",
"GET"
]
}
},
"SmoothStreaming":false,
"Compress":false,
"LambdaFunctionAssociations":{
"Quantity":0
},
"FunctionAssociations":{
"Quantity":0
},
"FieldLevelEncryptionId":"",
"CachePolicyId":"4135ea2d-6df8-44a3-9df3-4b5a84be39ad"
},
"CacheBehaviors":{
"Quantity":0
},
"CustomErrorResponses":{
"Quantity":0
},
"Comment":"%s",
"Logging":{
"Enabled":false,
"IncludeCookies":false,
"Bucket":"",
"Prefix":""
},
"PriceClass":"PriceClass_All",
"Enabled":true,
"ViewerCertificate":{
"CloudFrontDefaultCertificate":true
}
},
"Tags":{
"Items":[
{
"Key":"Name",
"Value":"%s"
}
]
}
}
}`
readOnlyAnonUserPolicyTemplate = `{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadPublicAccess",
"Principal": "*",
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:%s:s3:::%s/*"
]
}
]
}`
// ccoctlAWSResourceTagKeyPrefix is the prefix of the tag key applied to the AWS resources created/shared by ccoctl
ccoctlAWSResourceTagKeyPrefix = "openshift.io/cloud-credential-operator"
// ownedCcoctlAWSResourceTagValue is the value of the tag applied to the AWS resources created by ccoctl
ownedCcoctlAWSResourceTagValue = "owned"
// nameTagKey is the key of the "Name" tag applied to the AWS resources created by ccoctl
nameTagKey = "Name"
// cloudFrontCachingDisabledPolicyID is the ID of the policy that disables caching for a CloudFront distribution
cloudFrontCachingDisabledPolicyID = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad"
// cloudFrontDistributionDeployedStatus is status of the CloudFront when it is fully deployed
cloudFrontDistributionDeployedStatus = "Deployed"
// cloudFrontDistributionStatusCheckDelay is the time delay between subsequent status checks of CloudFront distribution
cloudFrontDistributionStatusCheckDelay = time.Second * 30
// cloudFrontOriginAccessIdentityActivationGracePeriod is a period to allow CloudFront Origin Access Identity to become
// active
cloudFrontOriginAccessIdentityActivationGracePeriod = time.Second * 30
// placeholderCloudFrontURL is a placeholder for cloudfront distribution URL that user needs to enter after generating files
placeholderCloudFrontURL = "<enter_cloudfront_distribution_url_here>"
// Generated identity provider files
oidcBucketFilename = "01-oidc-bucket.json"
oidcConfigurationFilename = "02-openid-configuration"
oidcKeysFilename = "03-keys.json"
iamIdentityProviderFilename = "04-iam-identity-provider.json"
cloudFrontOriginAccessIdentityFilename = "05-cloudfront-origin-access-identity.json"
putBucketPolicyToAllowOriginAccessIdentityFilename = "06-put-bucket-policy-to-allow-origin-access-identity.json"
blockPublicAccessToOidcBucketFilename = "07-block-public-access-to-oidc-bucket.json"
cloudFrontDistributionFilename = "08-cloudfront-distribution.json"
)
type JSONWebKeySet struct {
Keys []jose.JSONWebKey `json:"keys"`
}
func createIdentityProvider(client aws.Client, name, region, publicKeyPath, targetDir string, createPrivateS3, generateOnly bool) (string, error) {
// Create the S3 bucket and (if specified) a CloudFront Distribution to serve OIDC endpoint
bucketName := fmt.Sprintf("%s-oidc", name)
issuerURL, err := createOIDCEndpoint(client, bucketName, name, region, targetDir, createPrivateS3, generateOnly)
if err != nil {
return "", err
}
// Create the OIDC config file
if err := createOIDCConfiguration(client, bucketName, issuerURL, name, targetDir, createPrivateS3, generateOnly); err != nil {
return "", err
}
// Create the OIDC key list
if err := createJSONWebKeySet(client, publicKeyPath, bucketName, name, targetDir, createPrivateS3, generateOnly); err != nil {
return "", err
}
// Create the IAM Identity Provider
identityProviderARN, err := createIAMIdentityProvider(client, issuerURL, name, targetDir, generateOnly)
if err != nil {
return "", err
}
// Create the installer manifest file
if err := provisioning.CreateClusterAuthentication(issuerURL, targetDir); err != nil {
return "", err
}
return identityProviderARN, nil
}
func getTLSFingerprint(bucketURL string) (string, error) {
u, err := url.Parse(bucketURL)
if err != nil {
return "", err
}
urlWithPort := fmt.Sprintf("https://%s:443", u.Host)
var proxyUrl *url.URL
if proxyEnv := os.Getenv("HTTP_PROXY"); proxyEnv != "" {
proxyUrl, err = url.Parse(proxyEnv)
if err != nil {
fmt.Println("ERROR setting HTTP_PROXY")
}
fmt.Println("proxyUrl: ", proxyUrl)
}
tlsConfig := http.DefaultTransport.(*http.Transport).TLSClientConfig
c := &http.Client{
Transport: &http.Transport{
DialTLS: func(network, addr string) (net.Conn, error) {
conn, err := tls.Dial(network, addr, tlsConfig)
return conn, err
},
Proxy: http.ProxyURL(proxyUrl),
},
}
resp, err := c.Get(urlWithPort)
if err != nil {
return "", errors.Wrapf(err, "unable to validate URL %s to check existing Identity Provider", urlWithPort)
}
if resp.TLS == nil {
return "", errors.Wrapf(err, "unable to get TLS connection from URL %s", urlWithPort)
}
if resp.TLS.PeerCertificates == nil {
return "", errors.Wrapf(err, "unable to get TLS PeerCertificates from connection URL %s", urlWithPort)
}
certs := resp.TLS.PeerCertificates
numCerts := len(certs)
fingerprint := sha1.Sum(certs[numCerts-1].Raw)
var buf bytes.Buffer
for _, f := range fingerprint {
fmt.Fprintf(&buf, "%02X", f)
}
return buf.String(), nil
}
func createIAMIdentityProvider(client aws.Client, issuerURL, name, targetDir string, generateOnly bool) (string, error) {
var providerARN string
if generateOnly {
oidcIdentityProviderJSON := fmt.Sprintf(iamIdentityProviderTemplate, issuerURL, "<enter_tls_fingerprint_for_issuer_url_here>")
iamIdentityProviderFullPath := filepath.Join(targetDir, iamIdentityProviderFilename)
log.Printf("Saving AWS IAM Identity Provider locally at %s", iamIdentityProviderFullPath)
if err := ioutil.WriteFile(iamIdentityProviderFullPath, []byte(oidcIdentityProviderJSON), fileModeCcoctlDryRun); err != nil {
return "", errors.Wrap(err, fmt.Sprintf("Failed to save AWS IAM Identity Provider locally at %s", iamIdentityProviderFullPath))
}
} else {
fingerprint, err := getTLSFingerprint(issuerURL)
if err != nil {
return "", errors.Wrap(err, "failed to get fingerprint")
}
oidcProviderList, err := client.ListOpenIDConnectProviders(&iam.ListOpenIDConnectProvidersInput{})
if err != nil {
return "", errors.Wrap(err, "failed to fetch list of Identity Providers")
}
for _, provider := range oidcProviderList.OpenIDConnectProviderList {
ok, err := isExistingIdentifyProvider(client, *provider.Arn, name)
if err != nil {
return "", errors.Wrapf(err, "failed to check existing Identity Provider %s", *provider.Arn)
}
if ok {
providerARN = *provider.Arn
log.Printf("Existing Identity Provider found with ARN: %s", providerARN)
break
}
}
if len(providerARN) == 0 {
oidcOutput, err := client.CreateOpenIDConnectProvider(&iam.CreateOpenIDConnectProviderInput{
ClientIDList: []*string{
awssdk.String("openshift"),
awssdk.String("sts.amazonaws.com"),
},
ThumbprintList: []*string{
awssdk.String(fingerprint),
},
Url: awssdk.String(issuerURL),
})
if err != nil {
return "", errors.Wrap(err, "failed to create Identity Provider")
}
providerARN = *oidcOutput.OpenIDConnectProviderArn
_, err = client.TagOpenIDConnectProvider(&iam.TagOpenIDConnectProviderInput{
OpenIDConnectProviderArn: &providerARN,
Tags: []*iam.Tag{
{
Key: awssdk.String(fmt.Sprintf("%s/%s", ccoctlAWSResourceTagKeyPrefix, name)),
Value: awssdk.String(ownedCcoctlAWSResourceTagValue),
},
{
Key: awssdk.String(nameTagKey),
Value: awssdk.String(name),
},
},
})
if err != nil {
return "", errors.Wrapf(err, "failed to tag the identity provider with arn: %s", providerARN)
}
log.Printf("Identity Provider created with ARN: %s", providerARN)
}
}
return providerARN, nil
}
func createJSONWebKeySet(client aws.Client, publicKeyFilepath, bucketName, name, targetDir string, createPrivateS3, generateOnly bool) error {
jwks, err := provisioning.BuildJsonWebKeySet(publicKeyFilepath)
if err != nil {
return errors.Wrap(err, "failed to build JSON web key set from the public key")
}
if generateOnly {
oidcKeysFullPath := filepath.Join(targetDir, oidcKeysFilename)
log.Printf("Saving JSON web key set (JWKS) locally at %s", oidcKeysFullPath)
if err := ioutil.WriteFile(oidcKeysFullPath, jwks, fileModeCcoctlDryRun); err != nil {
return errors.Wrap(err, fmt.Sprintf("Failed to save JSON web key set (JWKS) locally at %s", oidcKeysFullPath))
}
} else {
_, err = client.PutObject(&s3.PutObjectInput{
Body: awssdk.ReadSeekCloser(bytes.NewReader(jwks)),
Bucket: awssdk.String(bucketName),
Key: awssdk.String(provisioning.KeysURI),
Tagging: awssdk.String(fmt.Sprintf("%s/%s=%s&%s=%s", ccoctlAWSResourceTagKeyPrefix, name, ownedCcoctlAWSResourceTagValue, nameTagKey, name)),
})
if err != nil {
return errors.Wrapf(err, "failed to upload JSON web key set (JWKS) in the S3 bucket %s", bucketName)
}
log.Printf("JSON web key set (JWKS) in the S3 bucket %s at %s updated", bucketName, provisioning.KeysURI)
}
return nil
}
func createOIDCConfiguration(client aws.Client, bucketName, issuerURL, name, targetDir string, createPrivateS3, generateOnly bool) error {
discoveryDocumentJSON := fmt.Sprintf(provisioning.DiscoveryDocumentTemplate, issuerURL, issuerURL, provisioning.KeysURI)
if generateOnly {
oidcConfigurationFullPath := filepath.Join(targetDir, oidcConfigurationFilename)
log.Printf("Saving discovery document locally at %s", oidcConfigurationFullPath)
if err := ioutil.WriteFile(oidcConfigurationFullPath, []byte(discoveryDocumentJSON), fileModeCcoctlDryRun); err != nil {
return errors.Wrap(err, fmt.Sprintf("Failed to save discovery document locally at %s", oidcConfigurationFullPath))
}
} else {
_, err := client.PutObject(&s3.PutObjectInput{
Body: awssdk.ReadSeekCloser(strings.NewReader(discoveryDocumentJSON)),
Bucket: awssdk.String(bucketName),
Key: awssdk.String(provisioning.DiscoveryDocumentURI),
Tagging: awssdk.String(fmt.Sprintf("%s/%s=%s&%s=%s", ccoctlAWSResourceTagKeyPrefix, name, ownedCcoctlAWSResourceTagValue, nameTagKey, name)),
})
if err != nil {
return errors.Wrapf(err, "failed to upload discovery document in the S3 bucket %s", bucketName)
}
log.Printf("OpenID Connect discovery document in the S3 bucket %s at %s updated", bucketName, provisioning.DiscoveryDocumentURI)
}
return nil
}
func createOIDCEndpoint(client aws.Client, bucketName, name, region, targetDir string, createPrivateS3, generateOnly bool) (string, error) {
partition, found := endpoints.PartitionForRegion([]endpoints.Partition{endpoints.AwsPartition(), endpoints.AwsCnPartition(), endpoints.AwsUsGovPartition()}, region)
if !found {
return "", fmt.Errorf("could not find AWS partition for provided region %s", region)
}
dnsSuffix := partition.DNSSuffix()
s3BucketURL := fmt.Sprintf("https://%s.s3.%s.%s", bucketName, region, dnsSuffix)
if generateOnly {
oidcBucketFilepath := filepath.Join(targetDir, oidcBucketFilename)
var oidcBucketJSON string
switch region {
case "us-east-1":
oidcBucketJSON = fmt.Sprintf(oidcBucketTemplateWithoutLocation, bucketName)
default:
oidcBucketJSON = fmt.Sprintf(oidcBucketTemplateWithLocation, bucketName, region)
}
log.Printf("Saving OIDC S3 bucket locally at %s", oidcBucketFilepath)
if err := ioutil.WriteFile(oidcBucketFilepath, []byte(oidcBucketJSON), fileModeCcoctlDryRun); err != nil {
return "", errors.Wrap(err, fmt.Sprintf("Failed to save OIDC S3 bucket locally at %s", oidcBucketFilepath))
}
if createPrivateS3 {
cloudFrontOriginAccessIdentityFilepath := filepath.Join(targetDir, cloudFrontOriginAccessIdentityFilename)
cloudFrontOriginAccessIdentityJSON := fmt.Sprintf(cloudFrontOriginAccessIdentityTemplate, name, fmt.Sprintf("%s/%s", ccoctlAWSResourceTagKeyPrefix, name))
log.Printf("Saving JSON to create CloudFront Origin Access Identity locally at %s", cloudFrontOriginAccessIdentityFilepath)
if err := ioutil.WriteFile(cloudFrontOriginAccessIdentityFilepath, []byte(cloudFrontOriginAccessIdentityJSON), fileModeCcoctlDryRun); err != nil {
return "", errors.Wrap(err, fmt.Sprintf("Failed to save JSON to create CloudFront Origin Access Identity locally at %s", cloudFrontOriginAccessIdentityFilepath))
}
putBucketPolicyToAllowOriginAccessIdentityFilepath := filepath.Join(targetDir, putBucketPolicyToAllowOriginAccessIdentityFilename)
putBucketPolicyToAllowOriginAccessIdentityJSON := fmt.Sprintf(putBucketPolicyToAllowOriginAccessIdentityTemplate, bucketName, bucketName)
log.Printf("Saving JSON to put bucket policy allowing access from CloudFront Origin Access Identity locally at %s", putBucketPolicyToAllowOriginAccessIdentityFilepath)
if err := ioutil.WriteFile(putBucketPolicyToAllowOriginAccessIdentityFilepath, []byte(putBucketPolicyToAllowOriginAccessIdentityJSON), fileModeCcoctlDryRun); err != nil {
return "", errors.Wrap(err, fmt.Sprintf("Failed to save JSON to put bucket policy allowing access from CloudFront Origin Access Identity locally at %s", putBucketPolicyToAllowOriginAccessIdentityFilepath))
}
blockPublicAccessToOidcBucketFilepath := filepath.Join(targetDir, blockPublicAccessToOidcBucketFilename)
blockPublicAccessToOidcBucketJSON := fmt.Sprintf(blockPublicAccessToOidcBucketTemplate, bucketName)
log.Printf("Saving JSON to block public access to OIDC S3 bucket locally at %s", oidcBucketFilepath)
if err := ioutil.WriteFile(blockPublicAccessToOidcBucketFilepath, []byte(blockPublicAccessToOidcBucketJSON), fileModeCcoctlDryRun); err != nil {
return "", errors.Wrap(err, fmt.Sprintf("Failed to save JSON to block public access to OIDC S3 bucket locally at %s", blockPublicAccessToOidcBucketFilepath))
}
cloudFrontDistributionFilepath := filepath.Join(targetDir, cloudFrontDistributionFilename)
cloudFrontDistributionJSON := fmt.Sprintf(cloudFrontDistributionWithTagsTemplate, name, bucketName, region, dnsSuffix, bucketName, region, dnsSuffix, bucketName, region, dnsSuffix, fmt.Sprintf("%s/%s", ccoctlAWSResourceTagKeyPrefix, name), name)
log.Printf("Saving JSON to create CloudFront Distribution locally at %s", cloudFrontDistributionFilepath)
if err := ioutil.WriteFile(cloudFrontDistributionFilepath, []byte(cloudFrontDistributionJSON), fileModeCcoctlDryRun); err != nil {
return "", errors.Wrap(err, fmt.Sprintf("Failed to save JSON to create CloudFront Distribution locally at %s", cloudFrontDistributionFilepath))
}
return placeholderCloudFrontURL, nil
}
} else {
s3BucketInput := &s3.CreateBucketInput{
Bucket: awssdk.String(bucketName),
}
// can't constrain to 'us-east-1'...it is the default and will error if you specify it
if region != "us-east-1" {
s3BucketInput.CreateBucketConfiguration = &s3.CreateBucketConfiguration{
LocationConstraint: awssdk.String(region),
}
}
_, err := client.CreateBucket(s3BucketInput)
if err != nil {
var aerr awserr.Error
if errors.As(err, &aerr) {
switch aerr.Code() {
case s3.ErrCodeBucketAlreadyOwnedByYou:
log.Printf("Bucket %s already exists and is owned by the user", bucketName)
default:
return "", errors.Wrap(aerr, "failed to create a bucket to store OpenID Connect configuration")
}
} else {
return "", errors.Wrap(err, "failed to create a bucket to store OpenID Connect configuration")
}
} else {
log.Print("Bucket ", bucketName, " created")
_, err = client.PutBucketTagging(&s3.PutBucketTaggingInput{
Bucket: awssdk.String(bucketName),
Tagging: &s3.Tagging{
TagSet: []*s3.Tag{
{
Key: awssdk.String(fmt.Sprintf("%s/%s", ccoctlAWSResourceTagKeyPrefix, name)),
Value: awssdk.String(ownedCcoctlAWSResourceTagValue),
},
{
Key: awssdk.String(nameTagKey),
Value: awssdk.String(name),
},
},
},
})
if err != nil {
return "", errors.Wrapf(err, "failed to tag the bucket %s", bucketName)
}
if createPrivateS3 {
createOriginAccessIdentityOutput, err := client.CreateCloudFrontOriginAccessIdentity(&cloudfront.CreateCloudFrontOriginAccessIdentityInput{
CloudFrontOriginAccessIdentityConfig: &cloudfront.OriginAccessIdentityConfig{
CallerReference: awssdk.String(name),
Comment: awssdk.String(fmt.Sprintf("%s/%s", ccoctlAWSResourceTagKeyPrefix, name)),
},
})
if err != nil {
return "", errors.Wrapf(err, "failed to create CloudFront origin access identity")
}
originAccessIdentityID := *createOriginAccessIdentityOutput.CloudFrontOriginAccessIdentity.Id
log.Printf("CloudFront origin access identity created with ID %s, waiting %s for it to become active", originAccessIdentityID, cloudFrontOriginAccessIdentityActivationGracePeriod)
// CloudFront origin access identity takes some time to become active. Adding policy to bucket before
// it gets active results in an error. Introducing a delay to avoid it.
time.Sleep(cloudFrontOriginAccessIdentityActivationGracePeriod)
oidcBucketPolicyAllowingOAIAccess := fmt.Sprintf(oidcBucketTemplateAllowingOAIAccess, originAccessIdentityID, bucketName)
_, err = client.PutBucketPolicy(&s3.PutBucketPolicyInput{
Bucket: awssdk.String(bucketName),
Policy: awssdk.String(oidcBucketPolicyAllowingOAIAccess),
})
if err != nil {
return "", errors.Wrapf(err, "failed to add policy for the bucket %s", bucketName)
}
log.Printf("Update policy for bucket %s to allow access from CloudFront origin access identity with ID %s", bucketName, originAccessIdentityID)
_, err = client.PutPublicAccessBlock(&s3.PutPublicAccessBlockInput{
Bucket: awssdk.String(bucketName),
PublicAccessBlockConfiguration: &s3.PublicAccessBlockConfiguration{
BlockPublicAcls: awssdk.Bool(true),
BlockPublicPolicy: awssdk.Bool(true),
IgnorePublicAcls: awssdk.Bool(true),
RestrictPublicBuckets: awssdk.Bool(true),
},
})
if err != nil {
return "", errors.Wrapf(err, "failed to block public access for the bucket %s", bucketName)
}
log.Printf("Blocked public access for the bucket %s", bucketName)
cloudFrontDistributionDomainName := fmt.Sprintf("%s.s3.%s.%s", bucketName, region, dnsSuffix)
cloudFrontDistributionOriginAccessIdentity := fmt.Sprintf("origin-access-identity/cloudfront/%s", originAccessIdentityID)
createCloudFrontDistributionOutput, err := client.CreateCloudFrontDistributionWithTags(&cloudfront.CreateDistributionWithTagsInput{
DistributionConfigWithTags: &cloudfront.DistributionConfigWithTags{
DistributionConfig: &cloudfront.DistributionConfig{
CallerReference: awssdk.String(name),
Comment: awssdk.String(fmt.Sprintf("%s/%s", ccoctlAWSResourceTagKeyPrefix, name)),
Origins: &cloudfront.Origins{
Items: []*cloudfront.Origin{
{
Id: awssdk.String(s3BucketURL),
DomainName: awssdk.String(cloudFrontDistributionDomainName),
S3OriginConfig: &cloudfront.S3OriginConfig{
OriginAccessIdentity: awssdk.String(cloudFrontDistributionOriginAccessIdentity),
},
},
},
Quantity: awssdk.Int64(1),
},
Enabled: awssdk.Bool(true),
DefaultCacheBehavior: &cloudfront.DefaultCacheBehavior{
AllowedMethods: &cloudfront.AllowedMethods{
Quantity: awssdk.Int64(2),
Items: []*string{
awssdk.String(cloudfront.MethodHead),
awssdk.String(cloudfront.MethodGet),
},
CachedMethods: &cloudfront.CachedMethods{
Quantity: awssdk.Int64(2),
Items: []*string{
awssdk.String(cloudfront.MethodHead),
awssdk.String(cloudfront.MethodGet),
},
},
},
TargetOriginId: awssdk.String(s3BucketURL),
ViewerProtocolPolicy: awssdk.String(cloudfront.ViewerProtocolPolicyHttpsOnly),
CachePolicyId: awssdk.String(cloudFrontCachingDisabledPolicyID),
},
ViewerCertificate: &cloudfront.ViewerCertificate{
CloudFrontDefaultCertificate: awssdk.Bool(true),
},
},
Tags: &cloudfront.Tags{
Items: []*cloudfront.Tag{
{
Key: awssdk.String(fmt.Sprintf("%s/%s", ccoctlAWSResourceTagKeyPrefix, name)),
Value: awssdk.String(ownedCcoctlAWSResourceTagValue),
},
{
Key: awssdk.String(nameTagKey),
Value: awssdk.String(name),
},
},
},
},
})
if err != nil {
return "", errors.Wrapf(err, "failed to create CloudFront Distribution")
}
distributionID := *createCloudFrontDistributionOutput.Distribution.Id
log.Printf("CloudFront distribution created with ID %s", distributionID)
for {
getCloudFrontDistributionOutput, err := client.GetCloudFrontDistribution(&cloudfront.GetDistributionInput{
Id: &distributionID,
})
if err != nil {
return "", errors.Wrapf(err, "failed to get CloudFront Distribution with ID %v", distributionID)
}
if *getCloudFrontDistributionOutput.Distribution.Status == cloudFrontDistributionDeployedStatus {
log.Printf("CloudFront distribution with ID %s is successfully deployed", distributionID)
break
}
log.Printf("Waiting %s for CloudFront distribution with ID %s to be deployed...", cloudFrontDistributionStatusCheckDelay, distributionID)
time.Sleep(cloudFrontDistributionStatusCheckDelay)
}
cloudFrontURL := fmt.Sprintf("https://%s", *createCloudFrontDistributionOutput.Distribution.DomainName)
return cloudFrontURL, nil
} else {
// Allow policies to control public access to the bucket.
// Continue to disallow ACLs from controlling public access to the bucket.
_, err = client.PutPublicAccessBlock(&s3.PutPublicAccessBlockInput{
Bucket: awssdk.String(bucketName),
PublicAccessBlockConfiguration: &s3.PublicAccessBlockConfiguration{
BlockPublicAcls: awssdk.Bool(true),
BlockPublicPolicy: awssdk.Bool(false),
IgnorePublicAcls: awssdk.Bool(true),
RestrictPublicBuckets: awssdk.Bool(false),
},
})
if err != nil {
return "", errors.Wrapf(err, "failed to allow public access for the bucket %s", bucketName)
}
partition, found := endpoints.PartitionForRegion([]endpoints.Partition{endpoints.AwsPartition(), endpoints.AwsCnPartition(), endpoints.AwsUsGovPartition()}, region)
if !found {
return "", fmt.Errorf("could not find AWS partition for provided region %s", region)
}
_, err = client.PutBucketPolicy(&s3.PutBucketPolicyInput{
Bucket: awssdk.String(bucketName),
Policy: awssdk.String(fmt.Sprintf(readOnlyAnonUserPolicyTemplate, partition.ID(), bucketName)),
})
if err != nil {
return "", errors.Wrapf(err, "failed to apply public access policy to the bucket %s", bucketName)
}
}
}
}
return s3BucketURL, nil
}
// isExistingIdentifyProvider checks if given identity provider is owned by given name prefix
func isExistingIdentifyProvider(client aws.Client, providerARN, namePrefix string) (bool, error) {
provider, err := client.GetOpenIDConnectProvider(&iam.GetOpenIDConnectProviderInput{
OpenIDConnectProviderArn: awssdk.String(providerARN),
})
if err != nil {
return false, errors.Wrapf(err, "failed to get Identity Provider with ARN %s", providerARN)
}
for _, tag := range provider.Tags {
if *tag.Key == fmt.Sprintf("%s/%s", ccoctlAWSResourceTagKeyPrefix, namePrefix) {
return true, nil
}
}
return false, nil
}
func createIdentityProviderCmd(cmd *cobra.Command, args []string) {
s, err := awsSession(CreateIdentityProviderOpts.Region)
if err != nil {
log.Fatal(err)
}
awsClient := aws.NewClientFromSession(s)
publicKeyPath := CreateIdentityProviderOpts.PublicKeyPath
if publicKeyPath == "" {
publicKeyPath = filepath.Join(CreateIdentityProviderOpts.TargetDir, provisioning.PublicKeyFile)
}
_, err = createIdentityProvider(awsClient, CreateIdentityProviderOpts.Name, CreateIdentityProviderOpts.Region, publicKeyPath, CreateIdentityProviderOpts.TargetDir, CreateIdentityProviderOpts.CreatePrivateS3Bucket, CreateIdentityProviderOpts.DryRun)
if err != nil {
log.Fatal(err)
}
}
// initEnvForCreateIdentityProviderCmd will ensure the destination directory is ready to receive the generated
// files, and will create the directory if necessary.
func initEnvForCreateIdentityProviderCmd(cmd *cobra.Command, args []string) {
if CreateIdentityProviderOpts.TargetDir == "" {
pwd, err := os.Getwd()
if err != nil {
log.Fatalf("Failed to get current directory: %s", err)
}
CreateIdentityProviderOpts.TargetDir = pwd
}
fPath, err := filepath.Abs(CreateIdentityProviderOpts.TargetDir)
if err != nil {
log.Fatalf("Failed to resolve full path: %s", err)
}
// create target dir if necessary
err = provisioning.EnsureDir(fPath)
if err != nil {
log.Fatalf("failed to create target directory at %s", fPath)
}
// create manifests dir if necessary
manifestsDir := filepath.Join(fPath, provisioning.ManifestsDirName)
err = provisioning.EnsureDir(manifestsDir)
if err != nil {
log.Fatalf("failed to create manifests directory at %s", manifestsDir)
}
}
// NewCreateIdentityProviderCmd provides the "create-identity-provider" subcommand
func NewCreateIdentityProviderCmd() *cobra.Command {
createIdentityProviderCmd := &cobra.Command{
Use: "create-identity-provider",
Short: "Create IAM identity provider",
Run: createIdentityProviderCmd,
PersistentPreRun: initEnvForCreateIdentityProviderCmd,
}
createIdentityProviderCmd.PersistentFlags().StringVar(&CreateIdentityProviderOpts.Name, "name", "", "User-defined name for all created AWS resources (can be separate from the cluster's infra-id)")
createIdentityProviderCmd.MarkPersistentFlagRequired("name")
createIdentityProviderCmd.PersistentFlags().StringVar(&CreateIdentityProviderOpts.Region, "region", "", "AWS region where the S3 OpenID Connect endpoint will be created")
createIdentityProviderCmd.MarkPersistentFlagRequired("region")
createIdentityProviderCmd.PersistentFlags().StringVar(&CreateIdentityProviderOpts.PublicKeyPath, "public-key-file", "", "Path to public ServiceAccount signing key")
createIdentityProviderCmd.PersistentFlags().BoolVar(&CreateIdentityProviderOpts.DryRun, "dry-run", false, "Skip creating objects, and just save what would have been created into files")
createIdentityProviderCmd.PersistentFlags().StringVar(&CreateIdentityProviderOpts.TargetDir, "output-dir", "", "Directory to place generated files (defaults to current directory)")
createIdentityProviderCmd.PersistentFlags().BoolVar(&CreateIdentityProviderOpts.CreatePrivateS3Bucket, "create-private-s3-bucket", false, "Create private S3 bucket with public CloudFront OIDC endpoint")
return createIdentityProviderCmd
}