-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathlambda_permissions.go
1341 lines (1187 loc) · 44.7 KB
/
lambda_permissions.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 sparta
import (
"encoding/json"
"fmt"
"strconv"
goftags "github.com/awslabs/goformation/v5/cloudformation/tags"
awsv2S3Types "github.com/aws/aws-sdk-go-v2/service/s3/types"
gof "github.com/awslabs/goformation/v5/cloudformation"
gofevents "github.com/awslabs/goformation/v5/cloudformation/events"
goflambda "github.com/awslabs/goformation/v5/cloudformation/lambda"
gofs3 "github.com/awslabs/goformation/v5/cloudformation/s3"
cfCustomResources "github.com/mweagle/Sparta/v3/aws/cloudformation/resources"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
////////////////////////////////////////////////////////////////////////////////
// Types to handle permissions & push source configuration
// describeInfoValue is a utility function that accepts
// some type of dynamic gocf value and transforms it into
// something that is `describe` output compatible
func describeInfoValue(dynamicValue string) string {
resolvedRef, resolvedRefErr := resolveResourceRef(dynamicValue)
if resolvedRefErr != nil {
return dynamicValue
}
switch resolvedRef.RefType {
case resourceLiteral:
return resolvedRef.ResourceName
default:
if resolvedRef.DisplayName != "" {
return resolvedRef.DisplayName
}
return dynamicValue
}
}
type descriptionNode struct {
Name string
Relation string
Color string
}
// LambdaPermissionExporter defines an interface for polymorphic collection of
// Permission entries that support specialization for additional resource generation.
type LambdaPermissionExporter interface {
// Export the permission object to a set of CloudFormation resources
// in the provided resources param. The targetLambdaFuncRef
// interface represents the Fn::GetAtt "Arn" JSON value
// of the parent Lambda target
export(serviceName string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error)
// Return a `describe` compatible output for the given permission. Return
// value is a list of tuples for node, edgeLabel
descriptionInfo() ([]descriptionNode, error)
}
////////////////////////////////////////////////////////////////////////////////
// START - BasePermission
//
// BasePermission (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html)
// type for common AWS Lambda permission data.
type BasePermission struct {
// The AWS account ID (without hyphens) of the source owner
SourceAccount string `json:"SourceAccount,omitempty"`
// The ARN of a resource that is invoking your function. This is
// either a full ARN literal or a goformation base64 encoded dynamic
// reference
SourceArn string `json:"SourceArn,omitempty"`
}
/*
func (perm *BasePermission) sourceArnExpr(joinParts ...string) string {
if perm.SourceArn == nil {
return ""
}
stringARN, stringARNOk := perm.SourceArn.(string)
if stringARNOk && strings.Contains(stringARN, "arn:aws:") {
return stringARN
}
// This is totally wrong - why are we trying to join the ARN prefix.
// Just have the user supply it. It's either a full ARN or a goformation
// Base64 ARN reef
var parts []string
if nil != joinParts {
parts = append(parts, joinParts...)
}
parts = append(parts,
spartaCF.DynamicValueToStringExpr(perm.SourceArn),
)
return gof.Join("", parts)
}
*/
func (perm BasePermission) export(principal string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error) {
lambdaPermission := &goflambda.Permission{
Action: "lambda:InvokeFunction",
FunctionName: gof.GetAtt(lambdaLogicalCFResourceName, "Arn"),
Principal: principal,
SourceArn: perm.SourceArn,
}
if perm.SourceAccount != "" {
lambdaPermission.SourceAccount = perm.SourceAccount
}
arnLiteral, arnLiteralErr := json.Marshal(lambdaPermission.SourceArn)
if nil != arnLiteralErr {
return "", arnLiteralErr
}
resourceName := CloudFormationResourceName("LambdaPerm%s",
principal,
string(arnLiteral),
lambdaLogicalCFResourceName)
template.Resources[resourceName] = lambdaPermission
return resourceName, nil
}
//
// END - BasePermission
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// START - S3Permission
//
// S3Permission struct implies that the S3 BasePermission.SourceArn should be
// updated (via PutBucketNotificationConfiguration) to automatically push
// events to the owning Lambda.
// See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources
// for more information.
type S3Permission struct {
BasePermission
// S3 events to register for (eg: `[]string{s3:GetObjectObjectCreated:*", "s3:ObjectRemoved:*"}`).
Events []string `json:"Events,omitempty"`
// S3.NotificationConfigurationFilter
// to scope event forwarding. See
// http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html
// for more information.
Filter awsv2S3Types.NotificationConfigurationFilter `json:"Filter,omitempty"`
}
func (perm S3Permission) export(serviceName string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error) {
targetLambdaResourceName, err := perm.BasePermission.export("s3.amazonaws.com",
lambdaFunctionDisplayName,
lambdaLogicalCFResourceName,
template,
lambdaFunctionCode,
logger)
if nil != err {
return "", errors.Wrap(err, "Failed to export S3 permission")
}
// Make sure the custom lambda that manages s3 notifications is provisioned.
configuratorResName, err := EnsureCustomResourceHandler(serviceName,
cfCustomResources.S3LambdaEventSource,
perm.SourceArn,
[]string{},
template,
lambdaFunctionCode,
logger)
if nil != err {
return "", errors.Wrap(err, "Exporting S3 permission")
}
// Add a custom resource invocation for this configuration
//////////////////////////////////////////////////////////////////////////////
newResource, newResourceError := newCloudFormationResource(cfCustomResources.S3LambdaEventSource,
logger)
if nil != newResourceError {
return "", newResourceError
}
// Setup the reqest for the S3 action
s3Resource, s3ResourceOK := newResource.(*cfCustomResources.S3LambdaEventSourceResource)
if !s3ResourceOK {
return "", fmt.Errorf("failed to access typed S3CustomResource")
}
s3Request := &cfCustomResources.S3LambdaEventSourceResourceRequest{
CustomResourceRequest: cfCustomResources.CustomResourceRequest{
ServiceToken: gof.GetAtt(configuratorResName, "Arn"),
},
BucketArn: perm.SourceArn,
LambdaTargetArn: gof.GetAtt(lambdaLogicalCFResourceName, "Arn"),
Events: perm.Events,
}
if nil != perm.Filter.Key {
s3Request.Filter = &perm.Filter
}
// Name?
resourceInvokerName := CloudFormationResourceName("ConfigS3",
lambdaLogicalCFResourceName,
perm.BasePermission.SourceAccount,
fmt.Sprintf("%#v", s3Request.Filter))
// Add it
s3Resource.AWSCloudFormationDependsOn = []string{
targetLambdaResourceName,
configuratorResName,
}
s3Resource.Properties = cfCustomResources.ToCustomResourceProperties(s3Request)
template.Resources[resourceInvokerName] = s3Resource
return "", nil
}
func (perm S3Permission) descriptionInfo() ([]descriptionNode, error) {
s3Events := ""
for _, eachEvent := range perm.Events {
s3Events = fmt.Sprintf("%s\n%s", eachEvent, s3Events)
}
nodes := make([]descriptionNode, 0)
if perm.Filter.Key == nil || len(perm.Filter.Key.FilterRules) == 0 {
nodes = append(nodes, descriptionNode{
Name: describeInfoValue(perm.SourceArn),
Relation: s3Events,
})
} else {
for _, eachFilter := range perm.Filter.Key.FilterRules {
filterRel := fmt.Sprintf("%s (%s = %s)",
s3Events,
eachFilter.Name,
*eachFilter.Value)
nodes = append(nodes, descriptionNode{
Name: describeInfoValue(perm.SourceArn),
Relation: filterRel,
})
}
}
return nodes, nil
}
// END - S3Permission
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// SNSPermission - START
// SNSPermission struct implies that the BasePermisison.SourceArn should be
// configured for subscriptions as part of this stacks provisioning.
// See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources
// for more information.
type SNSPermission struct {
BasePermission
}
func (perm SNSPermission) export(serviceName string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error) {
targetLambdaResourceName, err := perm.BasePermission.export(SNSPrincipal,
lambdaFunctionDisplayName,
lambdaLogicalCFResourceName,
template,
lambdaFunctionCode,
logger)
if nil != err {
return "", errors.Wrap(err, "Failed to export SNS permission")
}
// Make sure the custom lambda that manages s3 notifications is provisioned.
configuratorResName, err := EnsureCustomResourceHandler(serviceName,
cfCustomResources.SNSLambdaEventSource,
perm.SourceArn,
[]string{},
template,
lambdaFunctionCode,
logger)
if nil != err {
return "", errors.Wrap(err, "Exporing SNS permission handler")
}
// Add a custom resource invocation for this configuration
//////////////////////////////////////////////////////////////////////////////
newResource, newResourceError := newCloudFormationResource(cfCustomResources.SNSLambdaEventSource,
logger)
if nil != newResourceError {
return "", newResourceError
}
customResource := newResource.(*cfCustomResources.SNSLambdaEventSourceResource)
snsLambdaEventSourceRequest := &cfCustomResources.SNSLambdaEventSourceResourceRequest{
CustomResourceRequest: cfCustomResources.CustomResourceRequest{
ServiceToken: gof.GetAtt(configuratorResName, "Arn"),
},
LambdaTargetArn: gof.GetAtt(lambdaLogicalCFResourceName, "Arn"),
SNSTopicArn: perm.SourceArn,
}
// Name?
resourceInvokerName := CloudFormationResourceName("ConfigSNS",
lambdaLogicalCFResourceName,
perm.BasePermission.SourceAccount)
// Add it
customResource.AWSCloudFormationDependsOn = []string{
targetLambdaResourceName,
configuratorResName,
}
customResource.Properties = cfCustomResources.ToCustomResourceProperties(snsLambdaEventSourceRequest)
template.Resources[resourceInvokerName] = customResource
return "", nil
}
func (perm SNSPermission) descriptionInfo() ([]descriptionNode, error) {
nodes := []descriptionNode{
{
Name: describeInfoValue(perm.SourceArn),
Relation: "",
},
}
return nodes, nil
}
//
// END - SNSPermission
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// MessageBodyStorageOptions - START
// MessageBodyStorageOptions define additional options for storing SES
// message body content. By default, all rules associated with the owning
// SESPermission object will store message bodies if the MessageBodyStorage
// field is non-nil. Message bodies are by default prefixed with
// `ServiceName/RuleName/`, which can be overridden by specifying a non-empty
// ObjectKeyPrefix value. A rule can opt-out of message body storage
// with the DisableStorage field. See
// http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-action-s3.html
// for additional field documentation.
// The message body is saved as MIME (https://tools.ietf.org/html/rfc2045)
type MessageBodyStorageOptions struct {
ObjectKeyPrefix string
KmsKeyArn string
TopicArn string
DisableStorage bool
}
//
// END - MessageBodyStorageOptions
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// MessageBodyStorage - START
// MessageBodyStorage represents either a new S3 bucket or an existing S3 bucket
// to which SES message bodies should be stored.
// NOTE: New MessageBodyStorage create S3 buckets which will be orphaned after your
// service is deleted.
type MessageBodyStorage struct {
logicalBucketName string
bucketNameExpr string
cloudFormationS3BucketResourceName string
}
// BucketArn returns an Arn value that can be used as an
// lambdaFn.RoleDefinition.Privileges `Resource` value.
func (storage *MessageBodyStorage) BucketArn() string {
return gof.Join("", []string{
"arn:aws:s3:::",
storage.bucketNameExpr})
}
// BucketArnAllKeys returns an Arn value that can be used
// lambdaFn.RoleDefinition.Privileges `Resource` value. It includes
// the trailing `/*` wildcard to support item acccess
func (storage *MessageBodyStorage) BucketArnAllKeys() string {
return gof.Join("", []string{
"arn:aws:s3:::",
storage.bucketNameExpr,
"/*"})
}
func (storage *MessageBodyStorage) export(serviceName string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error) {
if storage.cloudFormationS3BucketResourceName != "" {
s3Bucket := &gofs3.Bucket{
Tags: []goftags.Tag{
{
Key: "sparta:logicalBucketName",
Value: storage.logicalBucketName,
},
},
}
s3Bucket.AWSCloudFormationDeletionPolicy = "Retain"
template.Resources[storage.cloudFormationS3BucketResourceName] = s3Bucket
lambdaResource, lambdaResourceExists := template.Resources[lambdaLogicalCFResourceName]
if !lambdaResourceExists {
appendErr := safeAppendDependency(lambdaResource, storage.cloudFormationS3BucketResourceName)
if appendErr != nil {
return "", errors.Errorf("Failed to append: %s", appendErr)
}
}
logger.Info().
Str("LogicalResourceName", storage.cloudFormationS3BucketResourceName).
Msg("Service will orphan S3 Bucket on deletion")
// Save the output
template.Outputs[storage.cloudFormationS3BucketResourceName] = gof.Output{
Description: "SES Message Body Bucket",
Value: gof.Ref(storage.cloudFormationS3BucketResourceName),
}
}
// Add the S3 Access policy
s3BodyStoragePolicy := &gofs3.BucketPolicy{
Bucket: storage.bucketNameExpr,
PolicyDocument: ArbitraryJSONObject{
"Version": "2012-10-17",
"Statement": []ArbitraryJSONObject{
{
"Sid": "PermitSESServiceToSaveEmailBody",
"Effect": "Allow",
"Principal": ArbitraryJSONObject{
"Service": "ses.amazonaws.com",
},
"Action": []string{"s3:PutObjectAcl", "s3:PutObject"},
"Resource": gof.Join("", []string{
"arn:aws:s3:::",
storage.bucketNameExpr,
"/*"}),
"Condition": ArbitraryJSONObject{
"StringEquals": ArbitraryJSONObject{
"aws:Referer": gof.Ref("AWS::AccountId"),
},
},
},
},
},
}
s3BucketPolicyResourceName := CloudFormationResourceName("SESMessageBodyBucketPolicy",
fmt.Sprintf("%#v", storage.bucketNameExpr))
template.Resources[s3BucketPolicyResourceName] = s3BodyStoragePolicy
// Return the name of the bucket policy s.t. the configurator resource
// is properly sequenced. The configurator will fail iff the Bucket Policies aren't
// applied b/c the SES Rule Actions check PutObject access to S3 buckets
return s3BucketPolicyResourceName, nil
}
// Return a function that
//
// END - MessageBodyStorage
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// ReceiptRule - START
// ReceiptRule represents an SES ReceiptRule
// (http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rules.html)
// value. To store message bodies, provide a non-nil MessageBodyStorage value
// to the owning SESPermission object
type ReceiptRule struct {
Name string
Disabled bool
Recipients []string
ScanDisabled bool
TLSPolicy string
TopicArn string
InvocationType string
BodyStorageOptions MessageBodyStorageOptions
}
func (rule *ReceiptRule) toResourceRule(serviceName string,
functionArnRef interface{},
messageBodyStorage *MessageBodyStorage) *cfCustomResources.SESLambdaEventSourceResourceRule {
resourceRule := &cfCustomResources.SESLambdaEventSourceResourceRule{
Name: rule.Name,
ScanEnabled: strconv.FormatBool(!rule.ScanDisabled),
Enabled: strconv.FormatBool(!rule.Disabled),
Actions: make([]*cfCustomResources.SESLambdaEventSourceResourceAction, 0),
Recipients: make([]string, 0),
}
resourceRule.Recipients = append(resourceRule.Recipients, rule.Recipients...)
if rule.TLSPolicy != "" {
resourceRule.TLSPolicy = rule.TLSPolicy
}
// If there is a MessageBodyStorage reference, push that S3Action
// to the head of the Actions list
if nil != messageBodyStorage && !rule.BodyStorageOptions.DisableStorage {
s3Action := &cfCustomResources.SESLambdaEventSourceResourceAction{
ActionType: "S3Action",
ActionProperties: map[string]interface{}{
"BucketName": messageBodyStorage.bucketNameExpr,
},
}
if rule.BodyStorageOptions.ObjectKeyPrefix != "" {
s3Action.ActionProperties["ObjectKeyPrefix"] = rule.BodyStorageOptions.ObjectKeyPrefix
}
if rule.BodyStorageOptions.KmsKeyArn != "" {
s3Action.ActionProperties["KmsKeyArn"] = rule.BodyStorageOptions.KmsKeyArn
}
if rule.BodyStorageOptions.TopicArn != "" {
s3Action.ActionProperties["TopicArn"] = rule.BodyStorageOptions.TopicArn
}
resourceRule.Actions = append(resourceRule.Actions, s3Action)
}
// There's always a lambda action
lambdaAction := &cfCustomResources.SESLambdaEventSourceResourceAction{
ActionType: "LambdaAction",
ActionProperties: map[string]interface{}{
"FunctionArn": functionArnRef,
},
}
lambdaAction.ActionProperties["InvocationType"] = rule.InvocationType
if rule.InvocationType == "" {
lambdaAction.ActionProperties["InvocationType"] = "Event"
}
if rule.TopicArn != "" {
lambdaAction.ActionProperties["TopicArn"] = rule.TopicArn
}
resourceRule.Actions = append(resourceRule.Actions, lambdaAction)
return resourceRule
}
//
// END - ReceiptRule
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// SESPermission - START
// SESPermission struct implies that the SES verified domain should be
// updated (via createReceiptRule) to automatically request or push events
// to the parent lambda
// See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources
// for more information. See http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-concepts.html
// for setting up email receiving.
type SESPermission struct {
BasePermission
InvocationType string /* RequestResponse, Event */
ReceiptRules []ReceiptRule
MessageBodyStorage *MessageBodyStorage
}
// NewMessageBodyStorageResource provisions a new S3 bucket to store message body
// content.
func (perm *SESPermission) NewMessageBodyStorageResource(bucketLogicalName string) (*MessageBodyStorage, error) {
if len(bucketLogicalName) <= 0 {
return nil, errors.New("NewMessageBodyStorageResource requires a unique, non-empty `bucketLogicalName` parameter ")
}
store := &MessageBodyStorage{
logicalBucketName: bucketLogicalName,
}
store.cloudFormationS3BucketResourceName = CloudFormationResourceName("SESMessageStoreBucket", bucketLogicalName)
store.bucketNameExpr = gof.Ref(store.cloudFormationS3BucketResourceName)
return store, nil
}
// NewMessageBodyStorageReference uses a pre-existing S3 bucket for MessageBody storage.
// Sparta assumes that prexistingBucketName exists and will add an S3::BucketPolicy
// to enable SES PutObject access.
func (perm *SESPermission) NewMessageBodyStorageReference(prexistingBucketName string) (*MessageBodyStorage, error) {
store := &MessageBodyStorage{}
store.bucketNameExpr = prexistingBucketName
return store, nil
}
func (perm SESPermission) export(serviceName string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error) {
targetLambdaResourceName, err := perm.BasePermission.export(SESPrincipal,
lambdaFunctionDisplayName,
lambdaLogicalCFResourceName,
template,
lambdaFunctionCode,
logger)
if nil != err {
return "", errors.Wrap(err, "Failed to export SES permission")
}
// MessageBody storage?
var dependsOn []string
if nil != perm.MessageBodyStorage {
s3Policy, s3PolicyErr := perm.MessageBodyStorage.export(serviceName,
lambdaFunctionDisplayName,
lambdaLogicalCFResourceName,
template,
lambdaFunctionCode,
logger)
if nil != s3PolicyErr {
return "", s3PolicyErr
}
if s3Policy != "" {
dependsOn = append(dependsOn, s3Policy)
}
}
// Make sure the custom lambda that manages SNS notifications is provisioned.
configuratorResName, err := EnsureCustomResourceHandler(serviceName,
cfCustomResources.SESLambdaEventSource,
perm.SourceArn,
dependsOn,
template,
lambdaFunctionCode,
logger)
if nil != err {
return "", errors.Wrap(err, "Ensuring custom resource handler for SES")
}
// Add a custom resource invocation for this configuration
//////////////////////////////////////////////////////////////////////////////
newResource, newResourceError := newCloudFormationResource(cfCustomResources.SESLambdaEventSource, logger)
if nil != newResourceError {
return "", newResourceError
}
customResource := newResource.(*cfCustomResources.SESLambdaEventSourceResource)
sesLambdaEventSourceRequest := &cfCustomResources.SESLambdaEventSourceResourceRequest{
CustomResourceRequest: cfCustomResources.CustomResourceRequest{
ServiceToken: gof.GetAtt(configuratorResName, "Arn"),
},
RuleSetName: "RuleSet",
}
///////////////////
// Build up the Rules
// If there aren't any rules, make one that forwards everything...
sesLength := 0
if perm.ReceiptRules == nil {
sesLength = 1
} else {
sesLength = len(perm.ReceiptRules)
}
sesRules := make([]*cfCustomResources.SESLambdaEventSourceResourceRule, sesLength)
if nil == perm.ReceiptRules {
sesRules[0] = &cfCustomResources.SESLambdaEventSourceResourceRule{
Name: "Default",
Actions: make([]*cfCustomResources.SESLambdaEventSourceResourceAction, 0),
ScanEnabled: strconv.FormatBool(false),
Enabled: strconv.FormatBool(true),
Recipients: []string{},
TLSPolicy: "Optional",
}
} else {
// Append all the user defined ones
for eachIndex, eachReceiptRule := range perm.ReceiptRules {
sesRules[eachIndex] = eachReceiptRule.toResourceRule(
serviceName,
gof.GetAtt(lambdaLogicalCFResourceName, "Arn"),
perm.MessageBodyStorage)
}
}
sesLambdaEventSourceRequest.Rules = sesRules
// Name?
resourceInvokerName := CloudFormationResourceName("ConfigSES",
lambdaLogicalCFResourceName,
perm.BasePermission.SourceAccount)
// Add it
customResource.AWSCloudFormationDependsOn = []string{
targetLambdaResourceName,
configuratorResName,
}
customResource.Properties = cfCustomResources.ToCustomResourceProperties(sesLambdaEventSourceRequest)
template.Resources[resourceInvokerName] = customResource
return "", nil
}
func (perm SESPermission) descriptionInfo() ([]descriptionNode, error) {
nodes := []descriptionNode{
{
Name: "SimpleEmailService",
Relation: "All verified domain(s) email",
},
}
return nodes, nil
}
//
// END - SESPermission
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// START - CloudWatchEventsRuleTarget
//
// CloudWatchEventsRuleTarget specifies additional input and JSON selection
// paths to apply prior to forwarding the event to a lambda function
type CloudWatchEventsRuleTarget struct {
Input string
InputPath string
}
//
// END - CloudWatchEventsRuleTarget
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// START - CloudWatchEventsRule
//
// CloudWatchEventsRule defines parameters for invoking a lambda function
// in response to specific CloudWatchEvents or cron triggers
type CloudWatchEventsRule struct {
Description string
// ArbitraryJSONObject filter for events as documented at
// http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CloudWatchEventsandEventPatterns.html
// Rules matches should use the JSON representation (NOT the string form). Sparta will serialize
// the map[string]interface{} to a string form during CloudFormation Template
// marshalling.
EventPattern map[string]interface{} `json:"EventPattern,omitempty"`
// Schedule pattern per http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/ScheduledEvents.html
ScheduleExpression string
RuleTarget *CloudWatchEventsRuleTarget `json:"RuleTarget,omitempty"`
}
// MarshalJSON customizes the JSON representation used when serializing to the
// CloudFormation template representation.
func (rule CloudWatchEventsRule) MarshalJSON() ([]byte, error) {
ruleJSON := map[string]interface{}{}
if rule.Description != "" {
ruleJSON["Description"] = rule.Description
}
if nil != rule.EventPattern {
eventPatternString, err := json.Marshal(rule.EventPattern)
if nil != err {
return nil, err
}
ruleJSON["EventPattern"] = string(eventPatternString)
}
if rule.ScheduleExpression != "" {
ruleJSON["ScheduleExpression"] = rule.ScheduleExpression
}
if nil != rule.RuleTarget {
ruleJSON["RuleTarget"] = rule.RuleTarget
}
return json.Marshal(ruleJSON)
}
//
// END - CloudWatchEventsRule
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// START - CloudWatchEventsPermission
//
// CloudWatchEventsPermission struct implies that the CloudWatchEvent sources
// should be configured as part of provisioning. The BasePermission.SourceArn
// isn't considered for this configuration. Each CloudWatchEventsRule struct
// in the Rules map is used to register for push based event notifications via
// `putRule` and `deleteRule`.
// See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources
// for more information.
type CloudWatchEventsPermission struct {
BasePermission
// Map of rule names to events that trigger the lambda function
Rules map[string]CloudWatchEventsRule
}
func (perm CloudWatchEventsPermission) export(serviceName string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error) {
// There needs to be at least one rule to apply
if len(perm.Rules) <= 0 {
return "", fmt.Errorf("function %s CloudWatchEventsPermission does not specify any expressions", lambdaFunctionDisplayName)
}
// Tell the user we're ignoring any Arns provided, since it doesn't make sense for this.
if perm.BasePermission.SourceArn != "" &&
perm.BasePermission.SourceArn != wildcardArn {
logger.Warn().
Interface("ARN", perm.BasePermission.SourceArn).
Msg("CloudWatchEvents do not support literal ARN values")
}
arnPermissionForRuleName := func(ruleName string) string {
return gof.Join("", []string{
"arn:aws:events:",
gof.Ref("AWS::Region"),
":",
gof.Ref("AWS::AccountId"),
":rule/",
ruleName})
}
// Add the permission to invoke the lambda function
uniqueRuleNameMap := make(map[string]int)
for eachRuleName, eachRuleDefinition := range perm.Rules {
// We need a stable unique name s.t. the permission is properly configured...
uniqueRuleName := CloudFormationResourceName(eachRuleName, lambdaFunctionDisplayName, serviceName)
uniqueRuleNameMap[uniqueRuleName]++
// Add the permission
basePerm := BasePermission{
SourceArn: arnPermissionForRuleName(uniqueRuleName),
}
_, exportErr := basePerm.export(CloudWatchEventsPrincipal,
lambdaFunctionDisplayName,
lambdaLogicalCFResourceName,
template,
lambdaFunctionCode,
logger)
if nil != exportErr {
return "", exportErr
}
cwEventsRuleTargetList := []gofevents.Rule_Target{
{
Arn: gof.GetAtt(lambdaLogicalCFResourceName, "Arn"),
Id: uniqueRuleName,
},
}
// Add the rule
eventsRule := &gofevents.Rule{
Name: uniqueRuleName,
Description: eachRuleDefinition.Description,
Targets: cwEventsRuleTargetList,
}
if nil != eachRuleDefinition.EventPattern && eachRuleDefinition.ScheduleExpression != "" {
return "", fmt.Errorf("rule %s CloudWatchEvents specifies both EventPattern and ScheduleExpression", eachRuleName)
}
if nil != eachRuleDefinition.EventPattern {
eventsRule.EventPattern = eachRuleDefinition.EventPattern
} else if eachRuleDefinition.ScheduleExpression != "" {
eventsRule.ScheduleExpression = eachRuleDefinition.ScheduleExpression
}
cloudWatchLogsEventResName := CloudFormationResourceName(fmt.Sprintf("%s-CloudWatchEventsRule", eachRuleName),
lambdaLogicalCFResourceName,
lambdaFunctionDisplayName)
template.Resources[cloudWatchLogsEventResName] = eventsRule
}
// Validate it
for _, eachCount := range uniqueRuleNameMap {
if eachCount != 1 {
return "", fmt.Errorf("integrity violation for CloudWatchEvent Rulenames: %#v", uniqueRuleNameMap)
}
}
return "", nil
}
func (perm CloudWatchEventsPermission) descriptionInfo() ([]descriptionNode, error) {
var ruleTriggers = " "
for eachName, eachRule := range perm.Rules {
filter := eachRule.ScheduleExpression
if filter == "" && eachRule.EventPattern != nil {
filter = fmt.Sprintf("%v", eachRule.EventPattern["source"])
}
ruleTriggers = fmt.Sprintf("%s-(%s)\n%s", eachName, filter, ruleTriggers)
}
nodes := []descriptionNode{
{
Name: "CloudWatch Events",
Relation: ruleTriggers,
},
}
return nodes, nil
}
//
// END - CloudWatchEventsPermission
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// START - EventBridgeRule
//
// EventBridgeRule defines parameters for invoking a lambda function
// in response to specific EventBridge triggers
type EventBridgeRule struct {
Description string
EventBusName string
// ArbitraryJSONObject filter for events as documented at
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-eventpattern
// Rules matches should use the JSON representation (NOT the string form). Sparta will serialize
// the map[string]interface{} to a string form during CloudFormation Template
// marshalling.
EventPattern map[string]interface{} `json:"EventPattern,omitempty"`
// Schedule pattern per
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-scheduleexpression
ScheduleExpression string
}
// MarshalJSON customizes the JSON representation used when serializing to the
// CloudFormation template representation.
func (rule EventBridgeRule) MarshalJSON() ([]byte, error) {
ruleJSON := map[string]interface{}{}
ruleJSON["Description"] = rule.Description
ruleJSON["EventBusName"] = rule.EventBusName
if rule.EventPattern != nil {
ruleJSON["EventPattern"] = rule.EventPattern
}
if rule.ScheduleExpression != "" {
ruleJSON["ScheduleExpression"] = rule.ScheduleExpression
}
return json.Marshal(ruleJSON)
}
//
// END - EventBridgeRule
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// START - EventBridgePermission
//
// EventBridgePermission struct implies that the EventBridge sources
// should be configured as part of provisioning. The BasePermission.SourceArn
// isn't considered for this configuration. Each EventBridge Rule or Schedule struct
// in the Rules map is used to register for push based event notifications via
// `putRule` and `deleteRule`.
// See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources
// for more information.
type EventBridgePermission struct {
BasePermission
// EventBridgeRule for this permission
Rule *EventBridgeRule
}
func (perm EventBridgePermission) export(serviceName string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error) {
// There needs to be at least one rule to apply
if perm.Rule == nil {
return "", fmt.Errorf("function %s EventBridgePermission does not specify any EventBridgeRule",
lambdaFunctionDisplayName)
}
// Name for the rule...
eventBridgeRuleResourceName := CloudFormationResourceName(fmt.Sprintf("EventBridge-%s", lambdaLogicalCFResourceName),
lambdaFunctionDisplayName)
// Tell the user we're ignoring any Arns provided, since it doesn't make sense for this.
if perm.BasePermission.SourceArn != "" &&
perm.BasePermission.SourceArn != wildcardArn {
logger.Warn().
Interface("ARN", perm.BasePermission.SourceArn).
Msg("EventBridge Events do not support literal ARN values")
}
// Add the permission
basePerm := BasePermission{
SourceArn: gof.GetAtt(eventBridgeRuleResourceName, "Arn"),
}
_, exportErr := basePerm.export(EventBridgePrincipal,
lambdaFunctionDisplayName,
lambdaLogicalCFResourceName,
template,
lambdaFunctionCode,
logger)