-
Notifications
You must be signed in to change notification settings - Fork 8
/
lambda.go
2501 lines (2447 loc) · 76.6 KB
/
lambda.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
package lib
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/acm"
"github.com/aws/aws-sdk-go/service/apigatewayv2"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/aws/aws-sdk-go/service/s3"
)
const (
lambdaAttrConcurrency = "concurrency"
lambdaAttrMemory = "memory"
lambdaAttrTimeout = "timeout"
lambdaAttrLogsTTLDays = "logs-ttl-days"
lambdaAttrConcurrencyDefault = 0
lambdaAttrMemoryDefault = 128
lambdaAttrTimeoutDefault = 300
lambdaAttrLogsTTLDaysDefault = 7
lambdaTriggerSQS = "sqs"
lambdaTrigerS3 = "s3"
lambdaTriggerDynamoDB = "dynamodb"
lambdaTriggerSchedule = "schedule"
lambdaTriggerEcr = "ecr"
lambdaTriggerApi = "api"
lambdaTriggerWebsocket = "websocket"
lambdaTriggerApiAttrDns = "dns"
lambdaTriggerApiAttrDomain = "domain"
lambdaDollarDefault = "$default"
lambdaDollarConnect = "$connect"
lambdaDollarDisconnect = "$disconnect"
lambdaAuthorizationType = "NONE"
lambdaRouteSelection = "${request.body.action}"
lambdaIntegrationMethod = "POST"
lambdaPayloadVersion = "1.0"
lambdaEnvVarApiID = "API_ID"
lambdaEnvVarWebsocketID = "WEBSOCKET_ID"
lambdaEventRuleNameSeparator = "___"
LambdaWebsocketSuffix = lambdaEventRuleNameSeparator + "websocket"
lambdaRuntimePython = "python3.9"
lambdaRuntimeGo = "go1.x"
lambdaRuntimeContainer = "container"
)
var lambdaClient *lambda.Lambda
var lambdaClientLock sync.RWMutex
func LambdaClientExplicit(accessKeyID, accessKeySecret, region string) *lambda.Lambda {
return lambda.New(SessionExplicit(accessKeyID, accessKeySecret, region))
}
func LambdaClient() *lambda.Lambda {
lambdaClientLock.Lock()
defer lambdaClientLock.Unlock()
if lambdaClient == nil {
lambdaClient = lambda.New(Session())
}
return lambdaClient
}
func LambdaSetConcurrency(ctx context.Context, lambdaName string, concurrency int, preview bool) error {
out, err := LambdaClient().GetFunctionConcurrencyWithContext(ctx, &lambda.GetFunctionConcurrencyInput{
FunctionName: aws.String(lambdaName),
})
if err != nil && !preview {
Logger.Println("error:", err)
return err
}
if out.ReservedConcurrentExecutions == nil {
out.ReservedConcurrentExecutions = aws.Int64(0)
}
if int(*out.ReservedConcurrentExecutions) != concurrency {
if !preview {
if concurrency > 0 {
_, err := LambdaClient().PutFunctionConcurrencyWithContext(ctx, &lambda.PutFunctionConcurrencyInput{
FunctionName: aws.String(lambdaName),
ReservedConcurrentExecutions: aws.Int64(int64(concurrency)),
})
if err != nil {
Logger.Println("error:", err)
return err
}
} else {
_, err := LambdaClient().DeleteFunctionConcurrencyWithContext(ctx, &lambda.DeleteFunctionConcurrencyInput{
FunctionName: aws.String(lambdaName),
})
if err != nil {
Logger.Println("error:", err)
return err
}
}
}
Logger.Printf(PreviewString(preview)+"updated concurrency: %d => %d\n", *out.ReservedConcurrentExecutions, concurrency)
}
return nil
}
func LambdaArn(ctx context.Context, name string) (string, error) {
var expectedErr error
var arn string
err := Retry(ctx, func() error {
out, err := LambdaClient().GetFunction(&lambda.GetFunctionInput{
FunctionName: aws.String(name),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == lambda.ErrCodeResourceNotFoundException {
expectedErr = err
return nil
}
return err
}
arn = *out.Configuration.FunctionArn
return nil
})
if err != nil {
Logger.Println("error:", err)
return "", err
}
if expectedErr != nil {
return "", expectedErr
}
return arn, nil
}
const lambdaEcrEventPattern = `{
"source": ["aws.ecr"],
"detail-type": ["ECR Image Action"],
"detail": {
"result": ["SUCCESS"]
}
}`
func LambdaEnsureTriggerEcr(ctx context.Context, infraLambda *InfraLambda, preview bool) ([]string, error) {
ruleName := fmt.Sprintf("%s%strigger_ecr", infraLambda.Name, lambdaEventRuleNameSeparator)
var permissionSids []string
var triggers []string
for _, trigger := range infraLambda.Trigger {
if trigger.Type == lambdaTriggerEcr {
triggers = append(triggers, trigger.Type)
break
}
}
if len(triggers) > 0 {
var ruleArn string
out, err := EventsClient().DescribeRuleWithContext(ctx, &cloudwatchevents.DescribeRuleInput{
Name: aws.String(ruleName),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if !ok || aerr.Code() != cloudwatchevents.ErrCodeResourceNotFoundException {
return nil, err
}
if !preview {
out, err := EventsClient().PutRuleWithContext(ctx, &cloudwatchevents.PutRuleInput{
Name: aws.String(ruleName),
EventPattern: aws.String(lambdaEcrEventPattern),
Tags: []*cloudwatchevents.Tag{{
Key: aws.String(infraSetTagName),
Value: aws.String(infraLambda.infraSetName),
}},
})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
ruleArn = *out.RuleArn
}
Logger.Println(PreviewString(preview)+"created ecr rule:", ruleName)
} else {
if *out.EventPattern != lambdaEcrEventPattern {
err := fmt.Errorf("ecr rule misconfigured: %s %s != %s", ruleName, lambdaEcrEventPattern, *out.EventPattern)
Logger.Println("error:", err)
return nil, err
}
ruleArn = *out.Arn
}
sid, err := lambdaEnsurePermission(ctx, infraLambda.Name, "events.amazonaws.com", ruleArn, preview)
if err != nil {
Logger.Println("error:", err)
return nil, err
}
permissionSids = append(permissionSids, sid)
var targets []*cloudwatchevents.Target
err = Retry(ctx, func() error {
var err error
targets, err = EventsListRuleTargets(ctx, ruleName)
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == "ResourceNotFoundException" {
return nil
}
return err
})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
switch len(targets) {
case 0:
if !preview {
_, err := EventsClient().PutTargetsWithContext(ctx, &cloudwatchevents.PutTargetsInput{
Rule: aws.String(ruleName),
Targets: []*cloudwatchevents.Target{{
Id: aws.String("1"),
Arn: aws.String(infraLambda.Arn),
}},
})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
}
Logger.Println(PreviewString(preview)+"created ecr rule target:", ruleName, infraLambda.Arn)
case 1:
if *targets[0].Arn != infraLambda.Arn {
err := fmt.Errorf("ecr rule is misconfigured with unknown target: %s %s", infraLambda.Arn, *targets[0].Arn)
Logger.Println("error:", err)
return nil, err
}
default:
var targetArns []string
for _, target := range targets {
targetArns = append(targetArns, *target.Arn)
}
err := fmt.Errorf("ecr rule is misconfigured with unknown targets: %s %v", infraLambda.Arn, targetArns)
Logger.Println("error:", err)
return nil, err
}
} else {
rules, err := EventsListRules(ctx)
if err != nil {
Logger.Println("error:", err)
return nil, err
}
for _, rule := range rules {
targets, err := EventsListRuleTargets(ctx, *rule.Name)
if err != nil {
Logger.Println("error:", err)
return nil, err
}
for _, target := range targets {
if *target.Arn == infraLambda.Arn && rule.EventPattern != nil && *rule.EventPattern == lambdaEcrEventPattern {
if !preview {
ids := []*string{}
for _, target := range targets {
ids = append(ids, target.Id)
}
_, err := EventsClient().RemoveTargetsWithContext(ctx, &cloudwatchevents.RemoveTargetsInput{
Rule: rule.Name,
Ids: ids,
})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
_, err = EventsClient().DeleteRuleWithContext(ctx, &cloudwatchevents.DeleteRuleInput{
Name: rule.Name,
})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
}
Logger.Println(PreviewString(preview)+"deleted ecr trigger:", infraLambda.Name)
break
}
}
}
}
return permissionSids, nil
}
func LambdaEnsureTriggerS3(ctx context.Context, infraLambda *InfraLambda, preview bool) ([]string, error) {
var permissionSids []string
events := []*string{
aws.String("s3:ObjectCreated:*"),
aws.String("s3:ObjectRemoved:*"),
}
var triggers []string
for _, trigger := range infraLambda.Trigger {
if trigger.Type == lambdaTrigerS3 {
triggers = append(triggers, trigger.Attr[0])
}
}
if len(triggers) > 0 {
for _, bucket := range triggers {
sid, err := lambdaEnsurePermission(ctx, infraLambda.Name, "s3.amazonaws.com", "arn:aws:s3:::"+bucket, preview)
if err != nil {
Logger.Println("error:", err)
return nil, err
}
permissionSids = append(permissionSids, sid)
s3Client, err := S3ClientBucketRegion(bucket)
if err != nil {
aerr, ok := err.(awserr.Error)
if !ok || aerr.Code() != s3.ErrCodeNoSuchBucket {
Logger.Println("error:", err)
return nil, err
}
s3Client = nil
}
var out *s3.NotificationConfiguration
if s3Client != nil {
out, err = s3Client.GetBucketNotificationConfigurationWithContext(ctx, &s3.GetBucketNotificationConfigurationRequest{
Bucket: aws.String(bucket),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if !ok || aerr.Code() != s3.ErrCodeNoSuchBucket {
Logger.Println("error:", err)
return nil, err
}
}
}
var existingEvents []*string
if out == nil {
out = &s3.NotificationConfiguration{
LambdaFunctionConfigurations: []*s3.LambdaFunctionConfiguration{},
}
}
for _, conf := range out.LambdaFunctionConfigurations {
if *conf.LambdaFunctionArn == infraLambda.Arn {
existingEvents = conf.Events
}
}
if !reflect.DeepEqual(existingEvents, events) {
var confs []*s3.LambdaFunctionConfiguration
for _, conf := range out.LambdaFunctionConfigurations {
if *conf.LambdaFunctionArn != infraLambda.Arn {
confs = append(confs, conf)
}
}
confs = append(confs, &s3.LambdaFunctionConfiguration{
LambdaFunctionArn: aws.String(infraLambda.Arn),
Events: events,
})
out.LambdaFunctionConfigurations = confs
if !preview {
err := Retry(ctx, func() error {
_, err := s3Client.PutBucketNotificationConfigurationWithContext(ctx, &s3.PutBucketNotificationConfigurationInput{
Bucket: aws.String(bucket),
NotificationConfiguration: out,
})
return err
})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
}
Logger.Printf(PreviewString(preview)+"updated bucket notifications for %s %s: %s => %s\n", bucket, infraLambda.Name, StringSlice(existingEvents), StringSlice(events))
}
}
}
buckets, err := S3Client().ListBucketsWithContext(ctx, &s3.ListBucketsInput{})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
for _, bucket := range buckets.Buckets {
out, err := S3ClientBucketRegionMust(*bucket.Name).GetBucketNotificationConfigurationWithContext(ctx, &s3.GetBucketNotificationConfigurationRequest{
Bucket: bucket.Name,
})
if err != nil {
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == s3.ErrCodeNoSuchBucket {
continue // recently delete buckets can still show up in listbuckets but fail with 404
}
Logger.Println("error:", err)
return nil, err
}
var confs []*s3.LambdaFunctionConfiguration
for _, conf := range out.LambdaFunctionConfigurations {
if *conf.LambdaFunctionArn != infraLambda.Arn || Contains(triggers, *bucket.Name) {
confs = append(confs, conf)
} else {
Logger.Println(PreviewString(preview)+"deleted bucket notification:", infraLambda.Name, *bucket.Name)
}
}
if len(confs) != len(out.LambdaFunctionConfigurations) && !preview {
out.LambdaFunctionConfigurations = confs
_, err := S3ClientBucketRegionMust(*bucket.Name).PutBucketNotificationConfigurationWithContext(ctx, &s3.PutBucketNotificationConfigurationInput{
Bucket: bucket.Name,
NotificationConfiguration: out,
})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
}
}
return permissionSids, nil
}
func lambdaRemoveUnusedPermissions(ctx context.Context, name string, permissionSids []string, preview bool) error {
out, err := LambdaClient().GetPolicyWithContext(ctx, &lambda.GetPolicyInput{
FunctionName: aws.String(name),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if !ok || aerr.Code() != lambda.ErrCodeResourceNotFoundException {
Logger.Println("error:", err)
return err
}
return nil
}
policy := IamPolicyDocument{}
err = json.Unmarshal([]byte(*out.Policy), &policy)
if err != nil {
Logger.Println("error:", err)
return err
}
for _, statement := range policy.Statement {
if !Contains(permissionSids, statement.Sid) {
if !preview {
_, err := LambdaClient().RemovePermissionWithContext(ctx, &lambda.RemovePermissionInput{
FunctionName: aws.String(name),
StatementId: aws.String(statement.Sid),
})
if err != nil {
Logger.Println("error:", err)
return err
}
}
Logger.Println(PreviewString(preview)+"deleted unused lambda permissions:", name, statement.Sid)
}
}
return nil
}
func lambdaAddPermission(ctx context.Context, sid, name, callerPrincipal, callerArn string) error {
region := Region()
account, err := StsAccount(ctx)
if err != nil {
Logger.Println("error:", err)
return err
}
_, err = LambdaClient().AddPermissionWithContext(ctx, &lambda.AddPermissionInput{
FunctionName: aws.String(fmt.Sprintf("arn:aws:lambda:%s:%s:function:%s", region, account, name)),
StatementId: aws.String(sid),
Action: aws.String("lambda:InvokeFunction"),
Principal: aws.String(callerPrincipal),
SourceArn: aws.String(callerArn),
})
return err
}
func lambdaEnsurePermission(ctx context.Context, name, callerPrincipal, callerArn string, preview bool) (string, error) {
sid := strings.ReplaceAll(callerPrincipal, ".", "-") + "__" + Last(strings.Split(callerArn, ":"))
sid = strings.ReplaceAll(sid, "$", "DOLLAR")
sid = strings.ReplaceAll(sid, "*", "ALL")
sid = strings.ReplaceAll(sid, "-", "_")
sid = strings.ReplaceAll(sid, "/", "__")
var expectedErr error
var policyString string
err := Retry(ctx, func() error {
out, err := LambdaClient().GetPolicyWithContext(ctx, &lambda.GetPolicyInput{
FunctionName: aws.String(name),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == lambda.ErrCodeResourceNotFoundException {
expectedErr = err
return nil
}
return err
}
policyString = *out.Policy
return nil
})
if err != nil {
Logger.Println("error:", err)
return "", err
}
if expectedErr != nil {
if !preview {
err := lambdaAddPermission(ctx, sid, name, callerPrincipal, callerArn)
if err != nil {
Logger.Println("error:", err)
return "", err
}
}
Logger.Println(PreviewString(preview)+"created lambda permission:", name, callerPrincipal, callerArn)
return sid, nil
}
needsUpdate := true
if policyString != "" {
policy := IamPolicyDocument{}
err := json.Unmarshal([]byte(policyString), &policy)
if err != nil {
Logger.Println("error:", err)
return "", err
}
for _, statement := range policy.Statement {
if statement.Sid == sid {
needsUpdate = false
break
}
}
}
if needsUpdate {
if !preview {
err := lambdaAddPermission(ctx, sid, name, callerPrincipal, callerArn)
if err != nil {
Logger.Println("error:", err)
return "", err
}
}
Logger.Println(PreviewString(preview)+"updated lambda permission:", name, callerPrincipal, callerArn)
return sid, nil
}
return sid, nil
}
func LambdaApiUri(ctx context.Context, lambdaName string) (string, error) {
account, err := StsAccount(ctx)
if err != nil {
Logger.Println("error:", err)
return "", err
}
uri := fmt.Sprintf(
"arn:aws:apigateway:%s:lambda:path/%s/functions/arn:aws:lambda:%s:%s:function:%s/invocations",
Region(),
LambdaClient().APIVersion,
Region(),
account,
lambdaName,
)
return uri, nil
}
func LambdaApiUriToLambdaName(apiUri string) string {
// "arn:aws:apigateway:%s:lambda:path/%s/functions/arn:aws:lambda:%s:%s:function:%s/invocations",
name := Last(strings.Split(apiUri, ":"))
name = strings.Split(name, "/")[0]
return name
}
func LambdaArnToLambdaName(arn string) string {
// "arn:aws:lambda:%s:%s:function:%s"
name := Last(strings.Split(arn, ":"))
return name
}
func lambdaEnsureTriggerApi(ctx context.Context, infraSetName, apiName, arnLambda string, protocolType string, preview bool) (*apigatewayv2.Api, error) {
if !Contains([]string{apigatewayv2.ProtocolTypeHttp, apigatewayv2.ProtocolTypeWebsocket}, protocolType) {
err := fmt.Errorf("invalid protocol type: %s", protocolType)
Logger.Println("error:", err)
return nil, err
}
api, err := Api(ctx, apiName)
if err != nil && err.Error() != ErrApiNotFound {
Logger.Println("error:", err)
return nil, err
}
if api == nil {
if !preview {
input := &apigatewayv2.CreateApiInput{
Name: aws.String(apiName),
ProtocolType: aws.String(protocolType),
Tags: map[string]*string{
infraSetTagName: aws.String(infraSetName),
},
}
if protocolType == apigatewayv2.ProtocolTypeWebsocket {
input.RouteKey = aws.String(lambdaDollarDefault)
input.Target = aws.String(arnLambda)
input.RouteSelectionExpression = aws.String(lambdaRouteSelection)
}
_, err := ApiClient().CreateApiWithContext(ctx, input)
if err != nil {
Logger.Println("error:", err)
return nil, err
}
api, err := Api(ctx, apiName)
if err != nil {
Logger.Println("error:", err)
return nil, err
}
return api, nil
}
Logger.Println(PreviewString(preview)+"created api:", apiName)
return nil, nil
}
if *api.ProtocolType != protocolType {
err := fmt.Errorf("api protocol type misconfigured for %s %s: %v != %v", apiName, *api.ApiId, *api.ProtocolType, protocolType)
Logger.Println("error:", err)
return nil, err
}
return api, nil
}
func lambdaEnsureTriggerApiIntegrationStageRoute(ctx context.Context, name, arnLambda, protocolType string, api *apigatewayv2.Api, timeoutMillis int64, preview bool) (string, error) {
if api == nil && preview {
Logger.Println(PreviewString(preview)+"created api integration:", name)
Logger.Println(PreviewString(preview)+"created api stage:", name)
Logger.Println(PreviewString(preview)+"created api route:", name)
return "", nil
}
account, err := StsAccount(ctx)
if err != nil {
Logger.Println("error:", err)
return "", err
}
var integrationId string
var getIntegrationsOut *apigatewayv2.GetIntegrationsOutput
if !(preview && api == nil) {
getIntegrationsOut, err = ApiClient().GetIntegrationsWithContext(ctx, &apigatewayv2.GetIntegrationsInput{
ApiId: api.ApiId,
MaxResults: aws.String(fmt.Sprint(500)),
})
if err != nil || len(getIntegrationsOut.Items) == 500 {
Logger.Println("error:", err)
return "", err
}
}
switch len(getIntegrationsOut.Items) {
case 0:
if !preview {
out, err := ApiClient().CreateIntegrationWithContext(ctx, &apigatewayv2.CreateIntegrationInput{
ApiId: api.ApiId,
IntegrationUri: aws.String(arnLambda),
ConnectionType: aws.String(apigatewayv2.ConnectionTypeInternet),
IntegrationType: aws.String(apigatewayv2.IntegrationTypeAwsProxy),
IntegrationMethod: aws.String(lambdaIntegrationMethod),
TimeoutInMillis: aws.Int64(timeoutMillis),
PayloadFormatVersion: aws.String(lambdaPayloadVersion),
})
if err != nil {
Logger.Println("error:", err)
return "", err
}
integrationId = *out.IntegrationId
}
Logger.Println(PreviewString(preview)+"created api integration:", name)
case 1:
integration := getIntegrationsOut.Items[0]
integrationId = *integration.IntegrationId
if *integration.ConnectionType != apigatewayv2.ConnectionTypeInternet {
err := fmt.Errorf("api connection type misconfigured for %s %s: %s != %s", name, *api.ApiId, *integration.ConnectionType, apigatewayv2.ConnectionTypeInternet)
Logger.Println("error:", err)
return "", err
}
if *integration.IntegrationType != apigatewayv2.IntegrationTypeAwsProxy {
err := fmt.Errorf("api integration type misconfigured for %s %s: %s != %s", name, *api.ApiId, *integration.IntegrationType, apigatewayv2.IntegrationTypeAwsProxy)
Logger.Println("error:", err)
return "", err
}
if *integration.IntegrationMethod != lambdaIntegrationMethod {
err := fmt.Errorf("api integration method misconfigured for %s %s: %s != %s", name, *api.ApiId, *integration.IntegrationMethod, lambdaIntegrationMethod)
Logger.Println("error:", err)
return "", err
}
if *integration.TimeoutInMillis != timeoutMillis {
err := fmt.Errorf("api timeout misconfigured for %s %s: %d != %d", name, *api.ApiId, *integration.TimeoutInMillis, timeoutMillis)
Logger.Println("error:", err)
return "", err
}
if *integration.PayloadFormatVersion != lambdaPayloadVersion {
err := fmt.Errorf("api payload format version misconfigured for %s %s: %s != %s", name, *api.ApiId, *integration.PayloadFormatVersion, lambdaPayloadVersion)
Logger.Println("error:", err)
return "", err
}
default:
err := fmt.Errorf("api has more than one integration: %s %v", name, Pformat(getIntegrationsOut.Items))
Logger.Println("error:", err)
return "", err
}
getStageOut, err := ApiClient().GetStageWithContext(ctx, &apigatewayv2.GetStageInput{
ApiId: api.ApiId,
StageName: aws.String(lambdaDollarDefault),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if !ok || aerr.Code() != apigatewayv2.ErrCodeNotFoundException {
Logger.Println("error:", err)
return "", err
}
if !preview {
_, err := ApiClient().CreateStageWithContext(ctx, &apigatewayv2.CreateStageInput{
ApiId: api.ApiId,
AutoDeploy: aws.Bool(true),
StageName: aws.String(lambdaDollarDefault),
})
if err != nil {
Logger.Println("error:", err)
return "", err
}
}
Logger.Println(PreviewString(preview)+"created api stage:", name)
} else {
if *getStageOut.StageName != lambdaDollarDefault {
err := fmt.Errorf("api stage name misconfigured for %s %s: %s != %s", name, *api.ApiId, *getStageOut.StageName, lambdaDollarDefault)
Logger.Println("error:", err)
return "", err
}
if !*getStageOut.AutoDeploy {
err := fmt.Errorf("api stage auto deploy misconfigured for %s %s, should be enabled", name, *api.ApiId)
Logger.Println("error:", err)
return "", err
}
}
getRoutesOut, err := ApiClient().GetRoutesWithContext(ctx, &apigatewayv2.GetRoutesInput{
ApiId: api.ApiId,
MaxResults: aws.String(fmt.Sprint(500)),
})
if err != nil || len(getRoutesOut.Items) == 500 {
Logger.Println("error:", err)
return "", err
}
var routeKeys []string
if protocolType == apigatewayv2.ProtocolTypeHttp {
routeKeys = []string{lambdaDollarDefault}
} else if protocolType == apigatewayv2.ProtocolTypeWebsocket {
routeKeys = []string{lambdaDollarDefault, lambdaDollarConnect, lambdaDollarDisconnect}
}
for _, routeKey := range routeKeys {
var routes []*apigatewayv2.Route
for _, route := range getRoutesOut.Items {
if *route.RouteKey == routeKey {
routes = append(routes, route)
}
}
switch len(routes) {
case 0:
if !preview {
_, err := ApiClient().CreateRouteWithContext(ctx, &apigatewayv2.CreateRouteInput{
ApiId: api.ApiId,
Target: aws.String(fmt.Sprintf("integrations/%s", integrationId)),
RouteKey: aws.String(routeKey),
AuthorizationType: aws.String(lambdaAuthorizationType),
ApiKeyRequired: aws.Bool(false),
})
if err != nil {
Logger.Println("error:", err)
return "", err
}
}
Logger.Println(PreviewString(preview)+"created api route:", name, routeKey)
case 1:
route := routes[0]
if *route.Target != fmt.Sprintf("integrations/%s", integrationId) {
err := fmt.Errorf("api route target misconfigured for %s %s: %s != %s", name, *api.ApiId, *route.Target, fmt.Sprintf("integrations/%s", integrationId))
Logger.Println("error:", err)
return "", err
}
if *route.RouteKey != routeKey {
err := fmt.Errorf("api route key misconfigured for %s %s: %s != %s", name, *api.ApiId, *route.RouteKey, routeKey)
Logger.Println("error:", err)
return "", err
}
if *route.AuthorizationType != lambdaAuthorizationType {
err := fmt.Errorf("api route authorization type misconfigured for %s %s: %s != %s", name, *api.ApiId, *route.AuthorizationType, lambdaAuthorizationType)
Logger.Println("error:", err)
return "", err
}
if *route.ApiKeyRequired {
err := fmt.Errorf("api route apiKeyRequired misconfigured for %s %s, should be disabled", name, *api.ApiId)
Logger.Println("error:", err)
return "", err
}
default:
err := fmt.Errorf("api has more than one route: %s %s %v", name, routeKey, Pformat(routes))
Logger.Println("error:", err)
return "", err
}
}
arn := fmt.Sprintf("arn:aws:execute-api:%s:%s:%s/*/*", Region(), account, *api.ApiId)
lambdaName := Last(strings.Split(arnLambda, ":"))
sid, err := lambdaEnsurePermission(ctx, lambdaName, "apigateway.amazonaws.com", arn, preview)
if err != nil {
Logger.Println("error:", err)
return "", err
}
return sid, nil
}
func lambdaEnsureTriggerApiDomainName(ctx context.Context, name, domain string, preview bool) error {
out, err := ApiClient().GetDomainNameWithContext(ctx, &apigatewayv2.GetDomainNameInput{
DomainName: aws.String(domain),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if !ok || aerr.Code() != apigatewayv2.ErrCodeNotFoundException {
Logger.Println("error:", err)
return err
}
certs, err := AcmListCertificates(ctx)
if err != nil {
Logger.Println("error:", err)
return err
}
arnCert := ""
for _, cert := range certs {
if *cert.DomainName == domain {
arnCert = *cert.CertificateArn
break
}
}
if arnCert == "" {
_, parentDomain, err := SplitOnce(domain, ".")
if err != nil {
Logger.Println("error:", err)
return err
}
certs, err := AcmListCertificates(ctx)
if err != nil {
Logger.Println("error:", err)
return err
}
for _, cert := range certs {
out, err := AcmClient().DescribeCertificateWithContext(ctx, &acm.DescribeCertificateInput{
CertificateArn: cert.CertificateArn,
})
if err != nil {
Logger.Println("error:", err)
return err
}
wildcard := fmt.Sprintf("*.%s", parentDomain)
if Contains(StringSlice(out.Certificate.SubjectAlternativeNames), wildcard) {
arnCert = *cert.CertificateArn
break
}
}
}
if arnCert == "" {
err := fmt.Errorf("no acm cert found for: %s", domain)
Logger.Println("error:", err)
return err
}
if !preview {
_, err = ApiClient().CreateDomainNameWithContext(ctx, &apigatewayv2.CreateDomainNameInput{
DomainName: aws.String(domain),
DomainNameConfigurations: []*apigatewayv2.DomainNameConfiguration{{
ApiGatewayDomainName: aws.String(domain),
CertificateArn: aws.String(arnCert),
EndpointType: aws.String(apigatewayv2.EndpointTypeRegional),
SecurityPolicy: aws.String(apigatewayv2.SecurityPolicyTls12),
}},
})
if err != nil {
Logger.Println("error:", err)
return err
}
}
Logger.Println(PreviewString(preview)+"created api domain:", name, domain)
} else {
if len(out.DomainNameConfigurations) != 1 || *out.DomainNameConfigurations[0].EndpointType != apigatewayv2.EndpointTypeRegional {
err := fmt.Errorf("api endpoint type misconfigured: %s", Pformat(out.DomainNameConfigurations))
Logger.Println("error:", err)
return err
}
if out.DomainNameConfigurations[0].SecurityPolicy == nil || *out.DomainNameConfigurations[0].SecurityPolicy != apigatewayv2.SecurityPolicyTls12 {
err := fmt.Errorf("api security policy misconfigured: %s", Pformat(out.DomainNameConfigurations[0].SecurityPolicy))
Logger.Println("error:", err)
return err
}
}
return nil
}
func lambdaEnsureTriggerApiDnsRecords(ctx context.Context, name, subDomain string, zone *route53.HostedZone, preview bool) error {
out, err := ApiClient().GetDomainNameWithContext(ctx, &apigatewayv2.GetDomainNameInput{
DomainName: aws.String(subDomain),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if !ok || aerr.Code() != apigatewayv2.ErrCodeNotFoundException {
Logger.Println("error:", err)
return err
}
Logger.Println(PreviewString(preview)+"created api dns:", name, subDomain)
} else {
records, err := Route53ListRecords(ctx, *zone.Id)
if err != nil {
Logger.Println("error:", err)
return err
}
found := false
needsUpdate := false
for _, record := range records {
if strings.TrimRight(*record.Name, ".") == subDomain && *record.Type == route53.RRTypeA {
found = true
if strings.TrimRight(*record.AliasTarget.DNSName, ".") != *out.DomainNameConfigurations[0].ApiGatewayDomainName {
needsUpdate = true
break
}
}
}
if !found || needsUpdate {
if !preview {
_, err := Route53Client().ChangeResourceRecordSetsWithContext(ctx, &route53.ChangeResourceRecordSetsInput{
HostedZoneId: zone.Id,
ChangeBatch: &route53.ChangeBatch{
Changes: []*route53.Change{{
Action: aws.String(route53.ChangeActionUpsert),
ResourceRecordSet: &route53.ResourceRecordSet{
Name: aws.String(subDomain),
Type: aws.String(route53.RRTypeA),
AliasTarget: &route53.AliasTarget{
DNSName: out.DomainNameConfigurations[0].ApiGatewayDomainName,
HostedZoneId: out.DomainNameConfigurations[0].HostedZoneId,
EvaluateTargetHealth: aws.Bool(false),
},
},
}},
},
})
if err != nil {
Logger.Println("error:", err)
return err
}
}
if needsUpdate {
Logger.Println(PreviewString(preview)+"updated api dns:", name, subDomain)
} else {
Logger.Println(PreviewString(preview)+"created api dns:", name, subDomain)
}
}
}
return nil
}
func lambdaEnsureTriggerApiDns(ctx context.Context, name, domain string, api *apigatewayv2.Api, preview bool) error {
zones, err := Route53ListZones(ctx)
if err != nil {
Logger.Println("error:", err)
return err
}
found := false
for _, zone := range zones {
if domain == strings.TrimRight(*zone.Name, ".") {
found = true
err := lambdaEnsureTriggerApiDomainName(ctx, name, domain, preview)
if err != nil {
Logger.Println("error:", err)
return err
}
err = lambdaEnsureTriggerApiDnsRecords(ctx, name, domain, zone, preview)
if err != nil {
Logger.Println("error:", err)
return err
}
err = lambdaEnsureTriggerApiMapping(ctx, name, domain, api, preview)
if err != nil {
Logger.Println("error:", err)
return err
}
break
}
}
if !found {
_, parentDomain, err := SplitOnce(domain, ".")
subDomain := domain
if err != nil {
Logger.Println("error:", err)
return err
}
for _, zone := range zones {
if parentDomain == strings.TrimRight(*zone.Name, ".") {
found = true
err := lambdaEnsureTriggerApiDomainName(ctx, name, subDomain, preview)
if err != nil {
Logger.Println("error:", err)
return err
}
err = lambdaEnsureTriggerApiDnsRecords(ctx, name, subDomain, zone, preview)
if err != nil {
Logger.Println("error:", err)
return err
}
err = lambdaEnsureTriggerApiMapping(ctx, name, subDomain, api, preview)
if err != nil {