forked from aws-cloudformation/cfn-lint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStateMachine.py
202 lines (178 loc) · 6.77 KB
/
StateMachine.py
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
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import json
from cfnlint.rules import CloudFormationLintRule, RuleMatch
class StateMachine(CloudFormationLintRule):
"""Check State Ma chine Definition"""
id = "E2532"
shortdesc = "Check State Machine Definition for proper syntax"
description = (
"Check the State Machine String Definition to make sure its JSON. "
"Validate basic syntax of the file to determine validity."
)
source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html"
tags = ["resources", "stepfunctions"]
def __init__(self):
"""Init"""
super().__init__()
self.resource_property_types.append("AWS::StepFunctions::StateMachine")
def _check_state_json(self, def_json, state_name, path):
"""Check State JSON Definition"""
matches = []
# https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-common-fields.html
common_state_keys = [
"Next",
"End",
"Type",
"Comment",
"InputPath",
"OutputPath",
]
common_state_required_keys = [
"Type",
]
state_key_types = {
"Pass": ["Result", "ResultPath", "Parameters"],
"Task": [
"Credentials",
"Resource",
"Parameters",
"ResultPath",
"ResultSelector",
"Retry",
"Catch",
"TimeoutSeconds",
"TimeoutSecondsPath",
"Parameters",
"HeartbeatSeconds",
"HeartbeatSecondsPath",
],
"Map": [
"MaxConcurrency",
"Iterator",
"ItemsPath",
"ItemProcessor",
"ItemReader",
"ItemSelector",
"ResultPath",
"ResultSelector",
"Retry",
"Catch",
"Parameters",
"ToleratedFailurePercentage",
"ItemBatcher",
],
"Choice": ["Choices", "Default"],
"Wait": ["Seconds", "Timestamp", "SecondsPath", "TimestampPath"],
"Succeed": [],
"Fail": ["Cause", "CausePath", "Error", "ErrorPath"],
"Parallel": [
"Branches",
"ResultPath",
"ResultSelector",
"Parameters",
"Retry",
"Catch",
],
}
state_required_types = {
"Pass": [],
"Task": ["Resource"],
"Choice": ["Choices"],
"Wait": [],
"Succeed": [],
"Fail": [],
"Parallel": ["Branches"],
}
for req_key in common_state_required_keys:
if req_key not in def_json:
message = (
f"State Machine Definition required key ({req_key}) for State"
f" ({state_name}) is missing"
)
matches.append(RuleMatch(path, message))
return matches
state_type = def_json.get("Type")
if state_type in state_key_types:
for state_key, _ in def_json.items():
if state_key not in common_state_keys + state_key_types.get(
state_type, []
):
message = (
f"State Machine Definition key ({state_key}) for State"
f" ({state_name}) of Type ({state_type}) is not valid"
)
matches.append(RuleMatch(path, message))
for req_key in common_state_required_keys + state_required_types.get(
state_type, []
):
if req_key not in def_json:
message = (
f"State Machine Definition required key ({req_key}) for State"
f" ({state_name}) of Type ({state_type}) is missing"
)
matches.append(RuleMatch(path, message))
return matches
else:
message = f"State Machine Definition Type ({state_type}) is not valid"
matches.append(RuleMatch(path, message))
return matches
def _check_definition_json(self, def_json, path):
"""Check JSON Definition"""
matches = []
top_level_keys = ["Comment", "StartAt", "TimeoutSeconds", "Version", "States"]
top_level_required_keys = ["StartAt", "States"]
for top_key, _ in def_json.items():
if top_key not in top_level_keys:
message = f"State Machine Definition key ({top_key}) is not valid"
matches.append(RuleMatch(path, message))
for req_key in top_level_required_keys:
if req_key not in def_json:
message = (
f"State Machine Definition required key ({req_key}) is missing"
)
matches.append(RuleMatch(path, message))
for state_name, state_value in def_json.get("States", {}).items():
matches.extend(self._check_state_json(state_value, state_name, path))
return matches
def check_value(self, value, path, fail_on_loads=True):
"""Check Definition Value"""
matches = []
try:
def_json = json.loads(value)
# pylint: disable=W0703
except Exception as err:
if fail_on_loads:
message = (
"State Machine Definition needs to be formatted as JSON. Error"
f" {err}"
)
matches.append(RuleMatch(path, message))
return matches
self.logger.debug("State Machine definition could not be parsed. Skipping")
return matches
matches.extend(self._check_definition_json(def_json, path))
return matches
def check_sub(self, value, path):
"""Check Sub Object"""
matches = []
if isinstance(value, list):
matches.extend(self.check_value(value[0], path, False))
elif isinstance(value, str):
matches.extend(self.check_value(value, path, False))
return matches
def match_resource_properties(self, properties, _, path, cfn):
"""Check CloudFormation Properties"""
matches = []
matches.extend(
cfn.check_value(
obj=properties,
key="DefinitionString",
path=path[:],
check_value=self.check_value,
check_sub=self.check_sub,
)
)
return matches