forked from aws/serverless-application-model
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsam_resources.py
More file actions
3412 lines (2920 loc) · 152 KB
/
sam_resources.py
File metadata and controls
3412 lines (2920 loc) · 152 KB
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
"""SAM macro definitions"""
import copy
import re
from contextlib import suppress
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union, cast
import samtranslator.model.eventsources
import samtranslator.model.eventsources.cloudwatchlogs
import samtranslator.model.eventsources.pull
import samtranslator.model.eventsources.push
import samtranslator.model.eventsources.scheduler
from samtranslator.feature_toggle.feature_toggle import FeatureToggle
from samtranslator.internal.intrinsics import resolve_string_parameter_in_resource
from samtranslator.internal.model.appsync import (
APPSYNC_PIPELINE_RESOLVER_JS_CODE,
APPSYNC_PIPELINE_RESOLVER_JS_RUNTIME,
AdditionalAuthenticationProviderType,
ApiCache,
ApiKey,
AppSyncRuntimeType,
CachingConfigType,
DataSource,
DomainName,
DomainNameApiAssociation,
DynamoDBConfigType,
FunctionConfiguration,
GraphQLApi,
GraphQLSchema,
LambdaAuthorizerConfigType,
LogConfigType,
OpenIDConnectConfigType,
Resolver,
SyncConfigType,
UserPoolConfigType,
)
from samtranslator.internal.schema_source import (
aws_serverless_capacity_provider,
aws_serverless_function,
aws_serverless_graphqlapi,
)
from samtranslator.internal.schema_source.common import PermissionsType, SamIntrinsicable
from samtranslator.internal.types import GetManagedPolicyMap
from samtranslator.internal.utils.utils import passthrough_value, remove_none_values
from samtranslator.intrinsics.resolver import IntrinsicsResolver
from samtranslator.metrics.method_decorator import cw_timer
from samtranslator.model import (
MutatedPassThroughProperty,
PassThroughProperty,
Property,
PropertyType,
Resource,
ResourceResolver,
ResourceTypeResolver,
SamResourceMacro,
ValidationRule,
)
from samtranslator.model.apigateway import (
ApiGatewayApiKey,
ApiGatewayDeployment,
ApiGatewayDomainName,
ApiGatewayDomainNameV2,
ApiGatewayStage,
ApiGatewayUsagePlan,
ApiGatewayUsagePlanKey,
)
from samtranslator.model.apigatewayv2 import ApiGatewayV2DomainName, ApiGatewayV2Stage
from samtranslator.model.architecture import ARM64, X86_64
from samtranslator.model.capacity_provider.generators import CapacityProviderGenerator
from samtranslator.model.cfn_attributes.deletion_policy import DeletionPolicy
from samtranslator.model.cloudformation import NestedStack
from samtranslator.model.connector.connector import (
UNSUPPORTED_CONNECTOR_PROFILE_TYPE,
ConnectorResourceError,
ConnectorResourceReference,
add_depends_on,
get_event_source_mappings,
get_resource_reference,
replace_depends_on_logical_id,
)
from samtranslator.model.connector_profiles.profile import (
ConnectorProfile,
get_profile,
profile_replace,
verify_profile_variables_replaced,
)
from samtranslator.model.dynamodb import DynamoDBTable
from samtranslator.model.exceptions import InvalidEventException, InvalidResourceException
from samtranslator.model.iam import IAMManagedPolicy, IAMRole, IAMRolePolicies
from samtranslator.model.intrinsics import (
fnGetAtt,
fnSub,
get_logical_id_from_intrinsic,
is_intrinsic,
is_intrinsic_if,
is_intrinsic_no_value,
make_and_condition,
make_conditional,
make_not_conditional,
ref,
)
from samtranslator.model.lambda_ import (
LAMBDA_TRACING_CONFIG_DISABLED,
LambdaAlias,
LambdaEventInvokeConfig,
LambdaFunction,
LambdaLayerVersion,
LambdaPermission,
LambdaUrl,
LambdaVersion,
)
from samtranslator.model.preferences.deployment_preference_collection import DeploymentPreferenceCollection
from samtranslator.model.resource_policies import ResourcePolicies
from samtranslator.model.role_utils import construct_role_for_resource
from samtranslator.model.sns import SNSTopic, SNSTopicPolicy
from samtranslator.model.sqs import SQSQueue, SQSQueuePolicy
from samtranslator.model.stepfunctions import StateMachineGenerator
from samtranslator.model.types import (
IS_BOOL,
IS_DICT,
IS_INT,
IS_LIST,
IS_STR,
IS_STR_ENUM,
PassThrough,
any_type,
dict_of,
list_of,
one_of,
)
from samtranslator.model.xray_utils import get_xray_managed_policy_name
from samtranslator.translator import logical_id_generator
from samtranslator.translator.arn_generator import ArnGenerator
from samtranslator.utils.types import Intrinsicable
from samtranslator.validator.value_validator import sam_expect
from .api.api_generator import ApiGenerator
from .api.http_api_generator import HttpApiGenerator
from .packagetype import IMAGE, ZIP
from .s3_utils.uri_parser import construct_image_code_object, construct_s3_location_object
from .tags.resource_tagging import get_tag_list
_CONDITION_CHAR_LIMIT = 255
class SamFunction(SamResourceMacro):
"""SAM function macro."""
resource_type = "AWS::Serverless::Function"
property_types = {
"FunctionName": PropertyType(False, one_of(IS_STR, IS_DICT)),
"Handler": PassThroughProperty(False),
"Runtime": PassThroughProperty(False),
"CodeUri": PassThroughProperty(False),
"ImageUri": PassThroughProperty(False),
"PackageType": PassThroughProperty(False),
"InlineCode": PassThroughProperty(False),
"DeadLetterQueue": PropertyType(False, IS_DICT),
"Description": PassThroughProperty(False),
"MemorySize": PassThroughProperty(False),
"Timeout": PassThroughProperty(False),
"VpcConfig": PassThroughProperty(False),
"Role": PropertyType(False, IS_STR),
"AssumeRolePolicyDocument": PropertyType(False, IS_DICT),
"Policies": PropertyType(False, one_of(IS_STR, IS_DICT, list_of(one_of(IS_STR, IS_DICT)))),
"RolePath": PassThroughProperty(False),
"PermissionsBoundary": PropertyType(False, IS_STR),
"Environment": PropertyType(False, dict_of(IS_STR, IS_DICT)),
"Events": PropertyType(False, dict_of(IS_STR, IS_DICT)),
"Tags": PropertyType(False, IS_DICT),
"PropagateTags": PropertyType(False, IS_BOOL),
"Tracing": PropertyType(False, one_of(IS_DICT, IS_STR)),
"KmsKeyArn": PassThroughProperty(False),
"DeploymentPreference": PropertyType(False, IS_DICT),
"ReservedConcurrentExecutions": PassThroughProperty(False),
"Layers": PropertyType(False, list_of(one_of(IS_STR, IS_DICT))),
"EventInvokeConfig": PropertyType(False, IS_DICT),
"EphemeralStorage": PassThroughProperty(False),
# Intrinsic functions in value of Alias property are not supported, yet
"AutoPublishAlias": PropertyType(False, one_of(IS_STR)),
"AutoPublishCodeSha256": PropertyType(False, one_of(IS_STR)),
"AutoPublishAliasAllProperties": Property(False, IS_BOOL),
"VersionDescription": PassThroughProperty(False),
"ProvisionedConcurrencyConfig": PassThroughProperty(False),
"FileSystemConfigs": PassThroughProperty(False),
"ImageConfig": PassThroughProperty(False),
"CodeSigningConfigArn": PassThroughProperty(False),
"Architectures": PassThroughProperty(False),
"SnapStart": PropertyType(False, IS_DICT),
"FunctionUrlConfig": PropertyType(False, IS_DICT),
"RuntimeManagementConfig": PassThroughProperty(False),
"LoggingConfig": PassThroughProperty(False),
"RecursiveLoop": PassThroughProperty(False),
"SourceKMSKeyArn": PassThroughProperty(False),
"CapacityProviderConfig": PropertyType(False, IS_DICT),
"FunctionScalingConfig": PropertyType(False, IS_DICT),
"VersionDeletionPolicy": PropertyType(False, IS_STR_ENUM(["Delete", "Retain"])),
"PublishToLatestPublished": PassThroughProperty(False),
"TenancyConfig": PassThroughProperty(False),
"DurableConfig": PropertyType(False, IS_DICT),
}
FunctionName: Optional[Intrinsicable[str]]
Handler: Optional[str]
Runtime: Optional[str]
CodeUri: Optional[Any]
ImageUri: Optional[str]
PackageType: Optional[str]
InlineCode: Optional[Any]
DeadLetterQueue: Optional[Dict[str, Any]]
Description: Optional[Intrinsicable[str]]
MemorySize: Optional[Intrinsicable[int]]
Timeout: Optional[Intrinsicable[int]]
VpcConfig: Optional[Dict[str, Any]]
Role: Optional[Intrinsicable[str]]
AssumeRolePolicyDocument: Optional[Dict[str, Any]]
Policies: Optional[List[Any]]
RolePath: Optional[PassThrough]
PermissionsBoundary: Optional[Intrinsicable[str]]
Environment: Optional[Dict[str, Any]]
Events: Optional[Dict[str, Any]]
Tags: Optional[Dict[str, Any]]
PropagateTags: Optional[bool]
Tracing: Optional[Intrinsicable[str]]
KmsKeyArn: Optional[Intrinsicable[str]]
DeploymentPreference: Optional[Dict[str, Any]]
ReservedConcurrentExecutions: Optional[Any]
Layers: Optional[List[Any]]
EventInvokeConfig: Optional[Dict[str, Any]]
EphemeralStorage: Optional[Dict[str, Any]]
AutoPublishAlias: Optional[Intrinsicable[str]]
AutoPublishCodeSha256: Optional[Intrinsicable[str]]
AutoPublishAliasAllProperties: Optional[bool]
VersionDescription: Optional[Intrinsicable[str]]
ProvisionedConcurrencyConfig: Optional[Dict[str, Any]]
FileSystemConfigs: Optional[Dict[str, Any]]
ImageConfig: Optional[Dict[str, Any]]
CodeSigningConfigArn: Optional[Intrinsicable[str]]
Architectures: Optional[List[Any]]
SnapStart: Optional[Dict[str, Any]]
FunctionUrlConfig: Optional[Dict[str, Any]]
LoggingConfig: Optional[Dict[str, Any]]
RecursiveLoop: Optional[str]
SourceKMSKeyArn: Optional[str]
CapacityProviderConfig: Optional[Dict[str, Any]]
FunctionScalingConfig: Optional[Dict[str, Any]]
PublishToLatestPublished: Optional[PassThrough]
VersionDeletionPolicy: Optional[Intrinsicable[str]]
TenancyConfig: Optional[Dict[str, Any]]
DurableConfig: Optional[Dict[str, Any]]
event_resolver = ResourceTypeResolver(
samtranslator.model.eventsources,
samtranslator.model.eventsources.pull,
samtranslator.model.eventsources.push,
samtranslator.model.eventsources.cloudwatchlogs,
samtranslator.model.eventsources.scheduler,
)
# DeadLetterQueue
dead_letter_queue_policy_actions = {"SQS": "sqs:SendMessage", "SNS": "sns:Publish"}
# Conditions
conditions: Dict[str, Any] = {} # TODO: Replace `Any` with something more specific
# Customers can refer to the following properties of SAM function
referable_properties = {
"Alias": LambdaAlias.resource_type,
"Version": LambdaVersion.resource_type,
# EventConfig auto created SQS and SNS
"DestinationTopic": SNSTopic.resource_type,
"DestinationQueue": SQSQueue.resource_type,
}
# Validation rules
__validation_rules__ = [
(ValidationRule.MUTUALLY_EXCLUSIVE, ["CapacityProviderConfig", "ProvisionedConcurrencyConfig"]),
(ValidationRule.MUTUALLY_EXCLUSIVE, ["CapacityProviderConfig", "VpcConfig"]),
(ValidationRule.CONDITIONAL_REQUIREMENT, ["FunctionScalingConfig", "CapacityProviderConfig"]),
(ValidationRule.CONDITIONAL_REQUIREMENT, ["VersionDeletionPolicy", "AutoPublishAlias"]),
# TODO: To enable these rules, we need to update translator test input/output files to property configure template
# to avoid fail-fast. eg: test with DeploymentPreference without AutoPublishAlias would fail fast before reaching testing state
# (ValidationRule.MUTUALLY_EXCLUSIVE, ["ImageUri", "InlineCode", "CodeUri"]),
# (ValidationRule.CONDITIONAL_REQUIREMENT, ["DeploymentPreference", "AutoPublishAlias"]),
# (ValidationRule.CONDITIONAL_REQUIREMENT, ["ProvisionedConcurrencyConfig", "AutoPublishAlias"]),
]
def resources_to_link(self, resources: Dict[str, Any]) -> Dict[str, Any]:
try:
return {"event_resources": self._event_resources_to_link(resources)}
except InvalidEventException as e:
raise InvalidResourceException(self.logical_id, e.message) from e
@cw_timer
def to_cloudformation(self, **kwargs): # type: ignore[no-untyped-def] # noqa: PLR0915
"""Returns the Lambda function, role, and event resources to which this SAM Function corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanilla CloudFormation Resources, to which this Function expands
:rtype: list
"""
resources: List[Any] = []
intrinsics_resolver: IntrinsicsResolver = kwargs["intrinsics_resolver"]
resource_resolver: ResourceResolver = kwargs["resource_resolver"]
mappings_resolver: Optional[IntrinsicsResolver] = kwargs.get("mappings_resolver")
conditions = kwargs.get("conditions", {})
feature_toggle = kwargs.get("feature_toggle")
# TODO: Skip pass schema_class=aws_serverless_function.Properties to skip schema validation for now.
# - adding this now would required update error message in error error_function_*_test.py
# - add this when we can verify that changing error message would not break customers
self.validate_before_transform(schema_class=None, collect_all_errors=False)
if self.DeadLetterQueue:
self._validate_dlq(self.DeadLetterQueue)
self._validate_tenancy_config_compatibility()
lambda_function = self._construct_lambda_function(intrinsics_resolver)
resources.append(lambda_function)
if self.ProvisionedConcurrencyConfig and not self.AutoPublishAlias:
raise InvalidResourceException(
self.logical_id,
"To set ProvisionedConcurrencyConfig AutoPublishALias must be defined on the function",
)
lambda_alias: Optional[LambdaAlias] = None
alias_name = ""
if self.AutoPublishAlias:
alias_name = self._get_resolved_alias_name("AutoPublishAlias", self.AutoPublishAlias, intrinsics_resolver)
code_sha256 = None
if self.AutoPublishCodeSha256:
code_sha256 = intrinsics_resolver.resolve_parameter_refs(self.AutoPublishCodeSha256)
if not isinstance(code_sha256, str):
raise InvalidResourceException(
self.logical_id,
"AutoPublishCodeSha256 must be a string",
)
# Lambda doesn't create a new version if the code in the unpublished version is the same as the
# previous published version. To address situations where users modify only the 'CodeUri' content,
# CloudFormation might not detect any changes in the Lambda function within the template, leading
# to deployment issues. To resolve this, we'll append codesha256 value to the description.
description = intrinsics_resolver.resolve_parameter_refs(self.Description)
if not description or isinstance(description, str):
lambda_function.Description = f"{description} {code_sha256}" if description else code_sha256
else:
lambda_function.Description = {"Fn::Join": [" ", [description, code_sha256]]}
lambda_version = self._construct_version(
lambda_function,
intrinsics_resolver=intrinsics_resolver,
resource_resolver=resource_resolver,
code_sha256=code_sha256,
)
lambda_alias = self._construct_alias(alias_name, lambda_function, lambda_version)
resources.append(lambda_version)
resources.append(lambda_alias)
if self.FunctionUrlConfig:
lambda_url = self._construct_function_url(lambda_function, lambda_alias, self.FunctionUrlConfig)
resources.append(lambda_url)
url_permission = self._construct_url_permission(lambda_function, lambda_alias, self.FunctionUrlConfig)
invoke_dual_auth_permission = self._construct_invoke_permission(
lambda_function, lambda_alias, self.FunctionUrlConfig
)
if url_permission and invoke_dual_auth_permission:
resources.append(url_permission)
resources.append(invoke_dual_auth_permission)
self._validate_deployment_preference_and_add_update_policy(
kwargs.get("deployment_preference_collection"),
lambda_alias,
intrinsics_resolver,
cast(IntrinsicsResolver, mappings_resolver), # TODO: better handle mappings_resolver's Optional
self.get_passthrough_resource_attributes(),
feature_toggle,
)
event_invoke_policies: List[Dict[str, Any]] = []
if self.EventInvokeConfig:
function_name = lambda_function.logical_id
event_invoke_resources, event_invoke_policies = self._construct_event_invoke_config(
function_name, alias_name, lambda_alias, intrinsics_resolver, conditions, self.EventInvokeConfig
)
resources.extend(event_invoke_resources)
managed_policy_map = kwargs.get("managed_policy_map", {})
get_managed_policy_map = kwargs.get("get_managed_policy_map")
execution_role = None
if lambda_function.Role is None:
execution_role = self._construct_role(
managed_policy_map,
event_invoke_policies,
intrinsics_resolver,
get_managed_policy_map,
)
lambda_function.Role = execution_role.get_runtime_attr("arn")
resources.append(execution_role)
try:
resources += self._generate_event_resources(
lambda_function,
execution_role,
kwargs["event_resources"],
intrinsics_resolver,
lambda_alias=lambda_alias,
original_template=kwargs.get("original_template"),
)
except InvalidEventException as e:
raise InvalidResourceException(self.logical_id, e.message) from e
self.propagate_tags(resources, self.Tags, self.PropagateTags)
return resources
def _construct_event_invoke_config( # noqa: PLR0913
self,
function_name: str,
alias_name: str,
lambda_alias: Optional[LambdaAlias],
intrinsics_resolver: IntrinsicsResolver,
conditions: Any,
event_invoke_config: Dict[str, Any],
) -> Tuple[List[Any], List[Dict[str, Any]]]:
"""
Create a `AWS::Lambda::EventInvokeConfig` based on the input dict `EventInvokeConfig`
"""
resources = []
policy_document = []
# Try to resolve.
resolved_event_invoke_config = intrinsics_resolver.resolve_parameter_refs(self.EventInvokeConfig)
logical_id = f"{function_name}EventInvokeConfig"
lambda_event_invoke_config = (
LambdaEventInvokeConfig(
logical_id=logical_id, depends_on=[lambda_alias.logical_id], attributes=self.resource_attributes
)
if lambda_alias
else LambdaEventInvokeConfig(logical_id=logical_id, attributes=self.resource_attributes)
)
dest_config = {}
input_dest_config = resolved_event_invoke_config.get("DestinationConfig")
if input_dest_config:
sam_expect(input_dest_config, self.logical_id, "EventInvokeConfig.DestinationConfig").to_be_a_map()
for config_name in ["OnSuccess", "OnFailure"]:
config_value = input_dest_config.get(config_name)
if config_value is not None:
sam_expect(
config_value, self.logical_id, f"EventInvokeConfig.DestinationConfig.{config_name}"
).to_be_a_map()
resource, destination, policy = self._validate_and_inject_resource(
config_value, config_name, logical_id, conditions
)
dest_config[config_name] = {"Destination": destination}
event_invoke_config["DestinationConfig"][config_name]["Destination"] = destination
if resource is not None:
resources.extend([resource])
if policy is not None:
policy_document.append(policy)
lambda_event_invoke_config.FunctionName = ref(function_name)
if alias_name:
lambda_event_invoke_config.Qualifier = alias_name
else:
lambda_event_invoke_config.Qualifier = "$LATEST"
lambda_event_invoke_config.DestinationConfig = dest_config
lambda_event_invoke_config.MaximumEventAgeInSeconds = resolved_event_invoke_config.get(
"MaximumEventAgeInSeconds"
)
lambda_event_invoke_config.MaximumRetryAttempts = resolved_event_invoke_config.get("MaximumRetryAttempts")
resources.extend([lambda_event_invoke_config])
return resources, policy_document
def _validate_and_inject_resource(
self, dest_config: Dict[str, Any], event: str, logical_id: str, conditions: Dict[str, Any]
) -> Tuple[Optional[Resource], Optional[Any], Dict[str, Any]]:
"""
For Event Invoke Config, if the user has not specified a destination ARN for SQS/SNS, SAM
auto creates a SQS and SNS resource with defaults. Intrinsics are supported in the Destination
ARN property, so to handle conditional ifs we have to inject if conditions in the auto created
SQS/SNS resources as well as in the policy documents.
"""
accepted_types_list = ["SQS", "SNS", "EventBridge", "Lambda", "S3Bucket"]
auto_inject_list = ["SQS", "SNS"]
resource: Optional[Union[SNSTopic, SQSQueue]] = None
policy = {}
destination = dest_config.get("Destination")
resource_logical_id = logical_id + event
if dest_config.get("Type") is None or dest_config.get("Type") not in accepted_types_list:
raise InvalidResourceException(
self.logical_id, "'Type: {}' must be one of {}".format(dest_config.get("Type"), accepted_types_list)
)
property_condition, dest_arn = self._get_or_make_condition(
dest_config.get("Destination"), logical_id, conditions
)
if dest_config.get("Destination") is None or property_condition is not None:
combined_condition = self._make_and_conditions(
self.get_passthrough_resource_attributes().get("Condition"), property_condition, conditions
)
if dest_config.get("Type") in auto_inject_list:
if dest_config.get("Type") == "SQS":
resource = SQSQueue(
resource_logical_id + "Queue", attributes=self.get_passthrough_resource_attributes()
)
if dest_config.get("Type") == "SNS":
resource = SNSTopic(
resource_logical_id + "Topic", attributes=self.get_passthrough_resource_attributes()
)
if resource:
if combined_condition:
resource.set_resource_attribute("Condition", combined_condition)
destination = (
make_conditional(property_condition, resource.get_runtime_attr("arn"), dest_arn)
if property_condition
else resource.get_runtime_attr("arn")
)
policy = self._add_event_invoke_managed_policy(dest_config, resource_logical_id, destination)
else:
raise InvalidResourceException(
self.logical_id, f"Destination is required if Type is not {auto_inject_list}"
)
if dest_config.get("Destination") is not None and property_condition is None:
policy = self._add_event_invoke_managed_policy(
dest_config, resource_logical_id, dest_config.get("Destination")
)
return resource, destination, policy
def _make_and_conditions(self, resource_condition: Any, property_condition: Any, conditions: Dict[str, Any]) -> Any:
if resource_condition is None:
return property_condition
if property_condition is None:
return resource_condition
and_condition = make_and_condition([{"Condition": resource_condition}, {"Condition": property_condition}])
condition_name = self._make_gen_condition_name(resource_condition + "AND" + property_condition, self.logical_id)
conditions[condition_name] = and_condition
return condition_name
def _get_or_make_condition(self, destination: Any, logical_id: str, conditions: Dict[str, Any]) -> Tuple[Any, Any]:
"""
This method checks if there is an If condition on Destination property. Since we auto create
SQS and SNS if the destination ARN is not provided, we need to make sure that If condition
is handled here.
True case: Only create the Queue/Topic if the condition is true
Destination: !If [SomeCondition, {Ref: AWS::NoValue}, queue-arn]
False case : Only create the Queue/Topic if the condition is false.
Destination: !If [SomeCondition, queue-arn, {Ref: AWS::NoValue}]
For the false case, we need to add a new condition that negates the existing condition, and
add that to the top-level Conditions.
"""
if destination is None:
return None, None
if is_intrinsic_if(destination):
dest_list = destination.get("Fn::If")
if is_intrinsic_no_value(dest_list[1]) and is_intrinsic_no_value(dest_list[2]):
return None, None
if is_intrinsic_no_value(dest_list[1]):
return dest_list[0], dest_list[2]
if is_intrinsic_no_value(dest_list[2]):
condition = dest_list[0]
not_condition = self._make_gen_condition_name("NOT" + condition, logical_id)
conditions[not_condition] = make_not_conditional(condition)
return not_condition, dest_list[1]
return None, None
def _make_gen_condition_name(self, name: str, hash_input: str) -> str:
# Make sure the property name is not over CFN limit (currently 255)
hash_digest = logical_id_generator.LogicalIdGenerator("", hash_input).gen()
condition_name: str = name + hash_digest
if len(condition_name) > _CONDITION_CHAR_LIMIT:
return input(condition_name)[:_CONDITION_CHAR_LIMIT]
return condition_name
def _get_resolved_alias_name(
self,
property_name: str,
original_alias_value: Intrinsicable[str],
intrinsics_resolver: IntrinsicsResolver,
) -> str:
"""
Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference
to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function was used), then this
method raises an exception. If alias name is just a plain string, it will return as is
:param dict or string original_alias_value: Value of Alias property as provided by the customer
:param samtranslator.intrinsics.resolver.IntrinsicsResolver intrinsics_resolver: Instance of the resolver that
knows how to resolve parameter references
:return string: Alias name
:raises InvalidResourceException: If the value is a complex intrinsic function that cannot be resolved
"""
# Try to resolve.
resolved_alias_name = intrinsics_resolver.resolve_parameter_refs(original_alias_value)
if not isinstance(resolved_alias_name, str):
# This is still a dictionary which means we are not able to completely resolve intrinsics
raise InvalidResourceException(
self.logical_id, f"'{property_name}' must be a string or a Ref to a template parameter"
)
return resolved_alias_name
def _validate_tenancy_config_compatibility(self) -> None:
if not self.TenancyConfig:
return
if self.ProvisionedConcurrencyConfig:
raise InvalidResourceException(
self.logical_id,
"Provisioned concurrency is not supported for functions enabled with tenancy configuration.",
)
if self.FunctionUrlConfig:
raise InvalidResourceException(
self.logical_id,
"Function URL is not supported for functions enabled with tenancy configuration.",
)
if self.SnapStart:
raise InvalidResourceException(
self.logical_id,
"SnapStart is not supported for functions enabled with tenancy configuration.",
)
if self.Events:
for event in self.Events.values():
event_type = event.get("Type")
if event_type not in ["Api", "HttpApi"]:
raise InvalidResourceException(
self.logical_id,
f"Event source '{event_type}' is not supported for functions enabled with tenancy configuration. Only Api and HttpApi event sources are supported.",
)
def _construct_lambda_function(self, intrinsics_resolver: IntrinsicsResolver) -> LambdaFunction:
"""Constructs and returns the Lambda function.
:returns: a list containing the Lambda function and execution role resources
:rtype: list
"""
lambda_function = LambdaFunction(
self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes
)
if self.FunctionName:
lambda_function.FunctionName = self.FunctionName
lambda_function.Handler = self.Handler
lambda_function.Runtime = self.Runtime
lambda_function.Description = self.Description
lambda_function.MemorySize = self.MemorySize
lambda_function.Timeout = self.Timeout
lambda_function.VpcConfig = self.VpcConfig
lambda_function.Role = self.Role
lambda_function.Environment = self.Environment
lambda_function.Code = self._construct_code_dict()
lambda_function.KmsKeyArn = self.KmsKeyArn
lambda_function.ReservedConcurrentExecutions = self.ReservedConcurrentExecutions
lambda_function.Tags = self._construct_tag_list(self.Tags)
lambda_function.Layers = self.Layers
lambda_function.FileSystemConfigs = self.FileSystemConfigs
lambda_function.ImageConfig = self.ImageConfig
lambda_function.PackageType = self.PackageType
lambda_function.Architectures = self.Architectures
lambda_function.SnapStart = self.SnapStart
lambda_function.EphemeralStorage = self.EphemeralStorage
tracing = intrinsics_resolver.resolve_parameter_refs(self.Tracing)
# Explicitly setting Trace to 'Disabled' is the same as omitting Tracing property.
if self.Tracing and tracing != LAMBDA_TRACING_CONFIG_DISABLED:
lambda_function.TracingConfig = {"Mode": self.Tracing}
if self.DeadLetterQueue:
lambda_function.DeadLetterConfig = {"TargetArn": self.DeadLetterQueue["TargetArn"]}
lambda_function.CodeSigningConfigArn = self.CodeSigningConfigArn
lambda_function.RuntimeManagementConfig = self.RuntimeManagementConfig # type: ignore[attr-defined]
lambda_function.LoggingConfig = self.LoggingConfig
lambda_function.TenancyConfig = self.TenancyConfig
lambda_function.RecursiveLoop = self.RecursiveLoop
lambda_function.DurableConfig = self.DurableConfig
# Transform capacity provider configuration
if self.CapacityProviderConfig:
lambda_function.CapacityProviderConfig = self._transform_capacity_provider_config()
# Pass through function scaling configuration
if self.FunctionScalingConfig:
lambda_function.FunctionScalingConfig = self.FunctionScalingConfig
# Pass through PublishToLatestPublished configuration
if self.PublishToLatestPublished is not None:
lambda_function.PublishToLatestPublished = self.PublishToLatestPublished
self._validate_package_type(lambda_function)
return lambda_function
def _transform_capacity_provider_config(self) -> Dict[str, Any]:
"""
Transform SAM CapacityProviderConfig to CloudFormation format.
Transforms from:
CapacityProviderConfig:
Arn: <capacity-provider-arn>
PerExecutionEnvironmentMaxConcurrency: <integer>
ExecutionEnvironmentMemoryGiBPerVCpu: <number>
To:
CapacityProviderConfig:
LambdaManagedInstancesCapacityProviderConfig:
CapacityProviderArn: <capacity-provider-arn>
PerExecutionEnvironmentMaxConcurrency: <integer>
ExecutionEnvironmentMemoryGiBPerVCpu: <number>
"""
if not self.CapacityProviderConfig:
return {}
# Validate CapacityProviderConfig using Pydantic model directly for comprehensive error collection
try:
validated_model = aws_serverless_function.CapacityProviderConfig.parse_obj(self.CapacityProviderConfig)
except Exception as e:
raise InvalidResourceException(self.logical_id, f"Invalid CapacityProviderConfig: {e!s}") from e
# Extract validated properties - cast to Any to handle SamIntrinsicable types
capacity_provider_arn: Optional[SamIntrinsicable[str]] = validated_model.Arn
max_concurrency: Optional[SamIntrinsicable[int]] = validated_model.PerExecutionEnvironmentMaxConcurrency
memory_to_vcpu_ratio: Optional[SamIntrinsicable[float]] = validated_model.ExecutionEnvironmentMemoryGiBPerVCpu
# Build the transformed structure
ec2_config: Dict[str, Any] = {"CapacityProviderArn": capacity_provider_arn}
if max_concurrency is not None:
ec2_config["PerExecutionEnvironmentMaxConcurrency"] = max_concurrency
if memory_to_vcpu_ratio is not None:
ec2_config["ExecutionEnvironmentMemoryGiBPerVCpu"] = memory_to_vcpu_ratio
return {"LambdaManagedInstancesCapacityProviderConfig": ec2_config}
def _add_event_invoke_managed_policy(
self, dest_config: Dict[str, Any], logical_id: str, dest_arn: Any
) -> Dict[str, Any]:
if dest_config and dest_config.get("Type"):
_type = dest_config.get("Type")
if _type == "SQS":
return IAMRolePolicies.sqs_send_message_role_policy(dest_arn, logical_id)
if _type == "SNS":
return IAMRolePolicies.sns_publish_role_policy(dest_arn, logical_id)
# Event Bridge and Lambda Arns are passthrough.
if _type == "EventBridge":
return IAMRolePolicies.event_bus_put_events_role_policy(dest_arn, logical_id)
if _type == "Lambda":
return IAMRolePolicies.lambda_invoke_function_role_policy(dest_arn, logical_id)
if _type == "S3Bucket":
return IAMRolePolicies.s3_send_event_payload_role_policy(dest_arn, logical_id)
return {}
def _construct_role(
self,
managed_policy_map: Dict[str, Any],
event_invoke_policies: List[Dict[str, Any]],
intrinsics_resolver: IntrinsicsResolver,
get_managed_policy_map: Optional[GetManagedPolicyMap] = None,
) -> IAMRole:
"""Constructs a Lambda execution role based on this SAM function's Policies property.
:returns: the generated IAM Role
:rtype: model.iam.IAMRole
"""
role_attributes = self.get_passthrough_resource_attributes()
assume_role_policy_document = (
self.AssumeRolePolicyDocument
if self.AssumeRolePolicyDocument is not None
else IAMRolePolicies.lambda_assume_role_policy()
)
managed_policy_arns = (
[ArnGenerator.generate_aws_managed_policy_arn("service-role/AWSLambdaBasicDurableExecutionRolePolicy")]
if self.DurableConfig
else [ArnGenerator.generate_aws_managed_policy_arn("service-role/AWSLambdaBasicExecutionRole")]
)
tracing = intrinsics_resolver.resolve_parameter_refs(self.Tracing)
# Do not add xray policy to generated IAM role if users explicitly specify 'Disabled' in Tracing property.
if self.Tracing and tracing != LAMBDA_TRACING_CONFIG_DISABLED:
managed_policy_name = get_xray_managed_policy_name()
managed_policy_arns.append(ArnGenerator.generate_aws_managed_policy_arn(managed_policy_name))
if self.VpcConfig:
managed_policy_arns.append(
ArnGenerator.generate_aws_managed_policy_arn("service-role/AWSLambdaVPCAccessExecutionRole")
)
function_policies = ResourcePolicies(
{"Policies": self.Policies},
# No support for policy templates in the "core"
policy_template_processor=None,
)
policy_documents = []
if self.DeadLetterQueue:
policy_documents.append(
IAMRolePolicies.dead_letter_queue_policy(
self.dead_letter_queue_policy_actions[self.DeadLetterQueue["Type"]],
self.DeadLetterQueue["TargetArn"],
)
)
if self.EventInvokeConfig and event_invoke_policies is not None:
policy_documents.extend(event_invoke_policies)
return construct_role_for_resource(
resource_logical_id=self.logical_id,
attributes=role_attributes,
managed_policy_map=managed_policy_map,
assume_role_policy_document=assume_role_policy_document,
resource_policies=function_policies,
managed_policy_arns=managed_policy_arns,
policy_documents=policy_documents,
role_path=self.RolePath,
permissions_boundary=self.PermissionsBoundary,
tags=self._construct_tag_list(self.Tags),
get_managed_policy_map=get_managed_policy_map,
)
def _validate_package_type(self, lambda_function: LambdaFunction) -> None:
"""
Validates Function based on the existence of Package type
"""
packagetype = lambda_function.PackageType or ZIP
if packagetype not in [ZIP, IMAGE]:
raise InvalidResourceException(
lambda_function.logical_id,
f"PackageType needs to be `{ZIP}` or `{IMAGE}`",
)
def _validate_package_type_zip() -> None:
if not all([lambda_function.Runtime, lambda_function.Handler]):
raise InvalidResourceException(
lambda_function.logical_id,
f"Runtime and Handler needs to be present when PackageType is of type `{ZIP}`",
)
if any([lambda_function.Code.get("ImageUri", False), lambda_function.ImageConfig]):
raise InvalidResourceException(
lambda_function.logical_id,
f"ImageUri or ImageConfig cannot be present when PackageType is of type `{ZIP}`",
)
def _validate_package_type_image() -> None:
if any([lambda_function.Handler, lambda_function.Runtime, lambda_function.Layers]):
raise InvalidResourceException(
lambda_function.logical_id,
f"Runtime, Handler, Layers cannot be present when PackageType is of type `{IMAGE}`",
)
if not lambda_function.Code.get("ImageUri"):
raise InvalidResourceException(
lambda_function.logical_id,
f"ImageUri needs to be present when PackageType is of type `{IMAGE}`",
)
_validate_per_package_type = {ZIP: _validate_package_type_zip, IMAGE: _validate_package_type_image}
# Call appropriate validation function based on the package type.
return _validate_per_package_type[packagetype]()
def _validate_dlq(self, dead_letter_queue: Dict[str, Any]) -> None:
"""Validates whether the DeadLetterQueue LogicalId is validation
:raise: InvalidResourceException
"""
# Validate required logical ids
valid_dlq_types = str(list(self.dead_letter_queue_policy_actions.keys()))
dlq_type = dead_letter_queue.get("Type")
if not dlq_type or not dead_letter_queue.get("TargetArn"):
raise InvalidResourceException(
self.logical_id,
"'DeadLetterQueue' requires Type and TargetArn properties to be specified.",
)
sam_expect(dlq_type, self.logical_id, "DeadLetterQueue.Type").to_be_a_string()
# Validate required Types
if dlq_type not in self.dead_letter_queue_policy_actions:
raise InvalidResourceException(self.logical_id, f"'DeadLetterQueue' requires Type of {valid_dlq_types}")
def _event_resources_to_link(self, resources: Dict[str, Any]) -> Dict[str, Any]:
event_resources = {}
if self.Events:
for logical_id, event_dict in self.Events.items():
try:
event_source = self.event_resolver.resolve_resource_type(event_dict).from_dict(
self.logical_id + logical_id, event_dict, logical_id
)
except (TypeError, AttributeError) as e:
raise InvalidEventException(logical_id, f"{e}") from e
event_resources[logical_id] = event_source.resources_to_link(resources)
return event_resources
@staticmethod
def order_events(event: Tuple[str, Any]) -> Any:
"""
Helper method for sorting Function Events. Returns a key to use in sorting this event
This is mainly used for HttpApi Events, where we need to evaluate the "$default" path (if any)
before we evaluate any of the other paths ("/", etc), so we can make sure we don't create any
redundant permissions. This sort places "$" before "/" or any alphanumeric characters.
:param event: tuple of (logical_id, event_dictionary) that contains event information
"""
logical_id, event_dict = event
if not isinstance(event_dict, dict):
return logical_id
return event_dict.get("Properties", {}).get("Path", logical_id)
def _generate_event_resources( # noqa: PLR0913
self,
lambda_function: LambdaFunction,
execution_role: Optional[IAMRole],
event_resources: Any,
intrinsics_resolver: IntrinsicsResolver,
lambda_alias: Optional[LambdaAlias] = None,
original_template: Optional[Dict[str, Any]] = None,
) -> List[Any]:
"""Generates and returns the resources associated with this function's events.
:param model.lambda_.LambdaFunction lambda_function: generated Lambda function
:param iam.IAMRole execution_role: generated Lambda execution role
:param implicit_api: Global Implicit API resource where the implicit APIs get attached to, if necessary
:param implicit_api_stage: Global implicit API stage resource where implicit APIs get attached to, if necessary
:param event_resources: All the event sources associated with this Lambda function
:param model.lambda_.LambdaAlias lambda_alias: Optional Lambda Alias resource if we want to connect the
event sources to this alias
:returns: a list containing the function's event resources
:rtype: list
"""
resources = []
if self.Events:
for logical_id, event_dict in sorted(self.Events.items(), key=SamFunction.order_events):
try:
eventsource = self.event_resolver.resolve_resource_type(event_dict).from_dict(
lambda_function.logical_id + logical_id, event_dict, logical_id
)
except TypeError as e:
raise InvalidEventException(logical_id, f"{e}") from e
kwargs = {
# When Alias is provided, connect all event sources to the alias and *not* the function
"function": lambda_alias or lambda_function,
"role": execution_role,
"intrinsics_resolver": intrinsics_resolver,
"original_template": original_template,
}
for name, resource in event_resources[logical_id].items():
kwargs[name] = resource
resources += eventsource.to_cloudformation(**kwargs)
return resources
def _construct_code_dict(self) -> Dict[str, Any]:
"""Constructs Lambda Code Dictionary based on the accepted SAM artifact properties such
as `InlineCode`, `CodeUri` and `ImageUri` and also raises errors if more than one of them is
defined. `PackageType` determines which artifacts are considered.
:raises InvalidResourceException when conditions on the SAM artifact properties are not met.
"""
# list of accepted artifacts
packagetype = self.PackageType or ZIP
artifacts = {}
if packagetype == ZIP:
artifacts = {"InlineCode": self.InlineCode, "CodeUri": self.CodeUri}
elif packagetype == IMAGE:
artifacts = {"ImageUri": self.ImageUri}
if packagetype not in [ZIP, IMAGE]:
raise InvalidResourceException(self.logical_id, f"invalid 'PackageType' : {packagetype}")
# Inline function for transformation of inline code.
# It accepts arbitrary argumemnts, because the arguments do not matter for the result.
def _construct_inline_code(*args: Any, **kwargs: Dict[str, Any]) -> Dict[str, Any]:
return {"ZipFile": self.InlineCode}
# dispatch mechanism per artifact on how it needs to be transformed.