ruby-cdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +87 -0
  3. data/LICENSE +21 -0
  4. data/README.md +303 -0
  5. data/THIRD_PARTY_NOTICES.md +327 -0
  6. data/data/spec/META.json +33 -0
  7. data/data/spec/model.json.gz +0 -0
  8. data/exe/ruby-cdk +9 -0
  9. data/lib/ruby-cdk.rb +4 -0
  10. data/lib/ruby_cdk/assets/builder.rb +122 -0
  11. data/lib/ruby_cdk/assets/hasher.rb +175 -0
  12. data/lib/ruby_cdk/assets/record.rb +49 -0
  13. data/lib/ruby_cdk/assets/uploader.rb +139 -0
  14. data/lib/ruby_cdk/assets/zipper.rb +108 -0
  15. data/lib/ruby_cdk/assets.rb +116 -0
  16. data/lib/ruby_cdk/bootstrap.rb +289 -0
  17. data/lib/ruby_cdk/cfn/resource.rb +93 -0
  18. data/lib/ruby_cdk/cfn.rb +10 -0
  19. data/lib/ruby_cdk/cli/arguments.rb +41 -0
  20. data/lib/ruby_cdk/cli/aws.rb +35 -0
  21. data/lib/ruby_cdk/cli/bootstrap.rb +63 -0
  22. data/lib/ruby_cdk/cli/diff.rb +98 -0
  23. data/lib/ruby_cdk/cli/failure.rb +80 -0
  24. data/lib/ruby_cdk/cli/io.rb +70 -0
  25. data/lib/ruby_cdk/cli/list.rb +46 -0
  26. data/lib/ruby_cdk/cli/new.rb +313 -0
  27. data/lib/ruby_cdk/cli/operation.rb +124 -0
  28. data/lib/ruby_cdk/cli/pairs.rb +32 -0
  29. data/lib/ruby_cdk/cli/report.rb +118 -0
  30. data/lib/ruby_cdk/cli/selection.rb +134 -0
  31. data/lib/ruby_cdk/cli/session.rb +290 -0
  32. data/lib/ruby_cdk/cli/shell.rb +30 -0
  33. data/lib/ruby_cdk/cli/synth.rb +58 -0
  34. data/lib/ruby_cdk/cli/validate.rb +101 -0
  35. data/lib/ruby_cdk/cli.rb +242 -0
  36. data/lib/ruby_cdk/constructs/bucket.rb +191 -0
  37. data/lib/ruby_cdk/constructs/function.rb +163 -0
  38. data/lib/ruby_cdk/constructs/grant.rb +90 -0
  39. data/lib/ruby_cdk/constructs/log_group.rb +115 -0
  40. data/lib/ruby_cdk/constructs/policy_statement.rb +161 -0
  41. data/lib/ruby_cdk/constructs/queue.rb +118 -0
  42. data/lib/ruby_cdk/constructs/role.rb +282 -0
  43. data/lib/ruby_cdk/constructs/table.rb +160 -0
  44. data/lib/ruby_cdk/constructs/topic.rb +88 -0
  45. data/lib/ruby_cdk/constructs.rb +56 -0
  46. data/lib/ruby_cdk/core/app.rb +146 -0
  47. data/lib/ruby_cdk/core/construct.rb +105 -0
  48. data/lib/ruby_cdk/core/elements.rb +107 -0
  49. data/lib/ruby_cdk/core/ids.rb +117 -0
  50. data/lib/ruby_cdk/core/stack.rb +291 -0
  51. data/lib/ruby_cdk/core/stateful.rb +156 -0
  52. data/lib/ruby_cdk/core.rb +15 -0
  53. data/lib/ruby_cdk/deploy/capabilities.rb +44 -0
  54. data/lib/ruby_cdk/deploy/deployer.rb +805 -0
  55. data/lib/ruby_cdk/deploy/errors.rb +72 -0
  56. data/lib/ruby_cdk/deploy/fakes.rb +546 -0
  57. data/lib/ruby_cdk/deploy/output/base.rb +167 -0
  58. data/lib/ruby_cdk/deploy/output/human.rb +37 -0
  59. data/lib/ruby_cdk/deploy/output/json.rb +80 -0
  60. data/lib/ruby_cdk/deploy/output/quiet.rb +20 -0
  61. data/lib/ruby_cdk/deploy/parameters.rb +86 -0
  62. data/lib/ruby_cdk/deploy/poller.rb +72 -0
  63. data/lib/ruby_cdk/deploy/ports.rb +205 -0
  64. data/lib/ruby_cdk/deploy/sdk_adapters.rb +608 -0
  65. data/lib/ruby_cdk/deploy/states.rb +62 -0
  66. data/lib/ruby_cdk/deploy.rb +25 -0
  67. data/lib/ruby_cdk/diff/compare.rb +141 -0
  68. data/lib/ruby_cdk/diff/normalizer.rb +83 -0
  69. data/lib/ruby_cdk/diff/render.rb +242 -0
  70. data/lib/ruby_cdk/diff/security.rb +322 -0
  71. data/lib/ruby_cdk/diff/statement.rb +256 -0
  72. data/lib/ruby_cdk/diff/template.rb +524 -0
  73. data/lib/ruby_cdk/diff.rb +62 -0
  74. data/lib/ruby_cdk/env.rb +42 -0
  75. data/lib/ruby_cdk/errors.rb +38 -0
  76. data/lib/ruby_cdk/fn.rb +409 -0
  77. data/lib/ruby_cdk/lazy.rb +55 -0
  78. data/lib/ruby_cdk/nag/config.rb +303 -0
  79. data/lib/ruby_cdk/nag/engine.rb +152 -0
  80. data/lib/ruby_cdk/nag/report.rb +86 -0
  81. data/lib/ruby_cdk/nag/rule.rb +171 -0
  82. data/lib/ruby_cdk/nag/rules/api_gateway_authorization.rb +91 -0
  83. data/lib/ruby_cdk/nag/rules/dynamodb_point_in_time_recovery.rb +45 -0
  84. data/lib/ruby_cdk/nag/rules/ebs_volume_encrypted.rb +41 -0
  85. data/lib/ruby_cdk/nag/rules/ec2_ingress_http.rb +48 -0
  86. data/lib/ruby_cdk/nag/rules/ec2_ingress_other_ports.rb +46 -0
  87. data/lib/ruby_cdk/nag/rules/iam_policy_admin_access.rb +60 -0
  88. data/lib/ruby_cdk/nag/rules/iam_policy_full_access.rb +55 -0
  89. data/lib/ruby_cdk/nag/rules/iam_user_credentials.rb +61 -0
  90. data/lib/ruby_cdk/nag/rules/lambda_runtime_supported.rb +88 -0
  91. data/lib/ruby_cdk/nag/rules/lambda_secret_environment.rb +61 -0
  92. data/lib/ruby_cdk/nag/rules/log_group_retention.rb +40 -0
  93. data/lib/ruby_cdk/nag/rules/policy_statements.rb +128 -0
  94. data/lib/ruby_cdk/nag/rules/rds_storage_encrypted.rb +65 -0
  95. data/lib/ruby_cdk/nag/rules/resource_policy_wildcard_principal.rb +58 -0
  96. data/lib/ruby_cdk/nag/rules/s3_public_access_block.rb +56 -0
  97. data/lib/ruby_cdk/nag/rules/security_group_ingress.rb +136 -0
  98. data/lib/ruby_cdk/nag/rules/stateful_deletion_policy.rb +46 -0
  99. data/lib/ruby_cdk/nag/rules.rb +51 -0
  100. data/lib/ruby_cdk/nag/values.rb +305 -0
  101. data/lib/ruby_cdk/nag.rb +60 -0
  102. data/lib/ruby_cdk/schema/normalizer.rb +164 -0
  103. data/lib/ruby_cdk/schema/property_schema.rb +22 -0
  104. data/lib/ruby_cdk/schema/schema.rb +195 -0
  105. data/lib/ruby_cdk/schema/sources/compiler.rb +56 -0
  106. data/lib/ruby_cdk/schema/sources/descriptor.rb +21 -0
  107. data/lib/ruby_cdk/schema/sources/download.rb +86 -0
  108. data/lib/ruby_cdk/schema/sources/provider_schemas.rb +47 -0
  109. data/lib/ruby_cdk/schema/sources/provider_type.rb +630 -0
  110. data/lib/ruby_cdk/schema/sources/regions.rb +86 -0
  111. data/lib/ruby_cdk/schema/sources/resource_specification.rb +94 -0
  112. data/lib/ruby_cdk/schema/sources/specification_type.rb +159 -0
  113. data/lib/ruby_cdk/schema/sources/update.rb +178 -0
  114. data/lib/ruby_cdk/schema/sources.rb +20 -0
  115. data/lib/ruby_cdk/schema/type_schema.rb +109 -0
  116. data/lib/ruby_cdk/schema/validator/corpus_check.rb +81 -0
  117. data/lib/ruby_cdk/schema/validator/policies.rb +48 -0
  118. data/lib/ruby_cdk/schema/validator/refs.rb +489 -0
  119. data/lib/ruby_cdk/schema/validator/report.rb +92 -0
  120. data/lib/ruby_cdk/schema/validator/rule.rb +119 -0
  121. data/lib/ruby_cdk/schema/validator/scans.rb +146 -0
  122. data/lib/ruby_cdk/schema/validator/structure.rb +469 -0
  123. data/lib/ruby_cdk/schema/validator/template.rb +203 -0
  124. data/lib/ruby_cdk/schema/validator/template_rules.rb +70 -0
  125. data/lib/ruby_cdk/schema/validator/walk.rb +122 -0
  126. data/lib/ruby_cdk/schema/validator.rb +159 -0
  127. data/lib/ruby_cdk/schema.rb +19 -0
  128. data/lib/ruby_cdk/synth/manifest.rb +128 -0
  129. data/lib/ruby_cdk/synth/resolver.rb +326 -0
  130. data/lib/ruby_cdk/synth/rules.rb +83 -0
  131. data/lib/ruby_cdk/synth/serializer.rb +120 -0
  132. data/lib/ruby_cdk/synth/writer.rb +31 -0
  133. data/lib/ruby_cdk/synth.rb +255 -0
  134. data/lib/ruby_cdk/test/capture.rb +133 -0
  135. data/lib/ruby_cdk/test/match.rb +426 -0
  136. data/lib/ruby_cdk/test/matcher.rb +290 -0
  137. data/lib/ruby_cdk/test/private/absent.rb +34 -0
  138. data/lib/ruby_cdk/test/private/conditions.rb +39 -0
  139. data/lib/ruby_cdk/test/private/cyclic.rb +160 -0
  140. data/lib/ruby_cdk/test/private/error.rb +48 -0
  141. data/lib/ruby_cdk/test/private/js.rb +326 -0
  142. data/lib/ruby_cdk/test/private/mappings.rb +39 -0
  143. data/lib/ruby_cdk/test/private/outputs.rb +39 -0
  144. data/lib/ruby_cdk/test/private/parameters.rb +39 -0
  145. data/lib/ruby_cdk/test/private/resources.rb +116 -0
  146. data/lib/ruby_cdk/test/private/section.rb +98 -0
  147. data/lib/ruby_cdk/test/private/sorting.rb +40 -0
  148. data/lib/ruby_cdk/test/private/sparse_matrix.rb +35 -0
  149. data/lib/ruby_cdk/test/private/type.rb +23 -0
  150. data/lib/ruby_cdk/test/template.rb +364 -0
  151. data/lib/ruby_cdk/test.rb +116 -0
  152. data/lib/ruby_cdk/values.rb +8 -0
  153. data/lib/ruby_cdk/version.rb +5 -0
  154. data/lib/ruby_cdk.rb +47 -0
  155. metadata +256 -0
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../../schema"
5
+ require_relative "../validator"
6
+
7
+ module RubyCdk
8
+ module Validation
9
+ # The corpus check (docs/07-testing.md §6): validates every template of a directory
10
+ # and says what was found. The templates are the CDK's own, synthesized and accepted
11
+ # by CloudFormation, so an error of any rule is a false positive: a bug in the model
12
+ # or in a rule. A warning is one the rule was made to give — an unknown type, a
13
+ # stack that deletes what it holds — and the check counts them by rule so that a run
14
+ # can be compared with the last.
15
+ #
16
+ # The safe defaults of architecture §7 belong to the tree, not to this component, so
17
+ # the caller hands the stateful types in (stateful_types:) the same way the umbrella
18
+ # hands them to rule V15.
19
+ class CorpusCheck
20
+ # What one template answered.
21
+ Finding = Data.define(:path, :errors, :warnings)
22
+
23
+ attr_reader :findings, :templates, :unparseable
24
+
25
+ # templates: every *.template.json under root, sorted. stateful_types: the types
26
+ # architecture §7 retains, as V15 takes them.
27
+ def initialize(root, stateful_types:)
28
+ @stateful_types = stateful_types
29
+ @templates = Dir[File.join(root, "**", "*.json")].sort
30
+ @findings = []
31
+ @unparseable = []
32
+ check_all
33
+ end
34
+
35
+ # Every error of every template, with its file: each one is a false positive to fix
36
+ # or to explain in known_false_positives.yml.
37
+ def errors
38
+ findings.flat_map { |finding| finding.errors.map { |issue| [ finding.path, issue ] } }
39
+ end
40
+
41
+ # Warnings by rule id: { "V1" => 220, "V15" => 103 }.
42
+ def warnings_by_rule
43
+ findings.flat_map { |finding| finding.warnings }.each_with_object(Hash.new(0)) do |issue, counts|
44
+ counts[issue.rule] += 1
45
+ end
46
+ end
47
+
48
+ # One line per file with something in it, as the weekly report prints it.
49
+ def to_s
50
+ lines = findings.select { |finding| finding.errors.any? || finding.warnings.any? }.map do |finding|
51
+ "#{path_of(finding.path)}: #{finding.errors.size} errors, #{finding.warnings.size} warnings"
52
+ end
53
+ [ "#{templates.size} templates, #{unparseable.size} unparseable, #{errors.size} errors, " \
54
+ "#{warnings_by_rule.sum { |_rule, count| count }} warnings #{warnings_by_rule.sort.map { |rule, count| "#{rule}=#{count}" }.join(" ")}",
55
+ *lines ].join("\n")
56
+ end
57
+
58
+ private
59
+
60
+ def check_all
61
+ templates.each do |path|
62
+ template = read(path)
63
+ next @unparseable << path if template.nil?
64
+
65
+ report = Validation.validate(template, stateful_types: @stateful_types)
66
+ @findings << Finding.new(path, report.errors, report.warnings)
67
+ end
68
+ end
69
+
70
+ def read(path)
71
+ JSON.parse(File.read(path))
72
+ rescue JSON::ParserError
73
+ nil
74
+ end
75
+
76
+ def path_of(path)
77
+ path.delete_prefix("#{File.dirname(File.dirname(path))}/")
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "rule"
4
+ require_relative "scans"
5
+ require_relative "template"
6
+
7
+ module RubyCdk
8
+ module Validation
9
+ module Rules
10
+ # V15: a resource type that holds data, deleted with the stack: DeletionPolicy is
11
+ # Delete on a stateful type. A warning, because the choice is the user's to make.
12
+ #
13
+ # The list of stateful types is core's (core/stateful.rb, architecture §7), and the
14
+ # validation component does not depend on core: the list is given when the rule is
15
+ # built, and without it the rule is not built at all rather than checking nothing in
16
+ # silence.
17
+ class StatefulDeletion < Rule
18
+ rule "V15"
19
+
20
+ # [ types ] with the types architecture §7 retains.
21
+ def initialize(types:)
22
+ @types = Array(types).map(&:to_s)
23
+ end
24
+
25
+ def call(context)
26
+ issues = []
27
+ Scans::Resources.each(context) do |name, body, path|
28
+ type = Template.resource_type(body)
29
+ next unless @types.include?(type) && deletes?(body["DeletionPolicy"])
30
+
31
+ issues << warning(path + [ "DeletionPolicy" ], "#{type} #{name} holds data, and DeletionPolicy is Delete: it goes with the stack",
32
+ hint: "leave deletion_policy: out to retain it, or pass deletion_policy: :retain or :snapshot")
33
+ end
34
+ issues
35
+ end
36
+
37
+ private
38
+
39
+ # True when the policy is Delete, or an Fn::If that can resolve to Delete.
40
+ def deletes?(policy)
41
+ return policy == "Delete" unless Template.function?(policy, "Fn::If") && policy["Fn::If"].is_a?(Array)
42
+
43
+ policy["Fn::If"][1, 2].any? { |branch| deletes?(branch) }
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,489 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../schema"
4
+ require_relative "rule"
5
+ require_relative "template"
6
+
7
+ module RubyCdk
8
+ module Validation
9
+ # The rules over what a template refers to: its references, its substitutions, its
10
+ # conditions, and the shapes CloudFormation takes only in some places (architecture
11
+ # §6: V8 to V11, V14, V20, V21 and V22).
12
+ #
13
+ # Every rule here has one in the CDK: the checks its include makes when it reads a
14
+ # template (packages/aws-cdk-lib/core/lib/helpers-internal/cfn-parse.ts and
15
+ # cloudformation-include/lib/cfn-include.ts, aws/aws-cdk@68b2516c), or the ones its
16
+ # engine makes (aws-cloudformation/cloudformation-validate@55ff54b6,
17
+ # src/cel-engine/src/rules/intrinsics.rs). Each rule says which, and follows it.
18
+ module Rules
19
+ # The places of a template where a reference can be written: every value of every
20
+ # section but Parameters and Mappings, which take literals. A template nested in a
21
+ # resource (the TemplateBody of an AWS::CloudFormation::Stack) is another template,
22
+ # with names of its own, and is left alone.
23
+ module Sites
24
+ NESTED_STACK = "AWS::CloudFormation::Stack"
25
+
26
+ module_function
27
+
28
+ # Yields [ value, segments, parameters_only ] for every value, in the order it is
29
+ # written. parameters_only is true in Conditions and in Rules, where a Ref reaches
30
+ # a parameter or a pseudo-parameter and nothing else. Answers an Enumerator
31
+ # without a block.
32
+ def each(context)
33
+ template = context.template
34
+ return unless template.is_a?(Hash)
35
+
36
+ template.each do |section, content|
37
+ next if Template::LITERAL_SECTIONS.include?(section)
38
+
39
+ parameters_only = Template::PARAMETERS_ONLY.include?(section)
40
+ if section == "Resources"
41
+ Template.resources(template).each do |name, body|
42
+ yield_resource(body, [ "Resources", name.to_s ], body["Type"] == NESTED_STACK) { |value, at| yield value, at, parameters_only }
43
+ end
44
+ else
45
+ Template.walk(content, section.to_s) { |value, at| yield value, at, parameters_only }
46
+ end
47
+ end
48
+ end
49
+
50
+ def yield_resource(body, at, nested)
51
+ body.each do |attribute, value|
52
+ if nested && attribute == "Properties" && value.is_a?(Hash)
53
+ value.each do |key, item|
54
+ next if key == "TemplateBody"
55
+
56
+ Template.walk(item, at + [ "Properties", key.to_s ]) { |found, path| yield found, path }
57
+ end
58
+ else
59
+ Template.walk(value, at + [ attribute.to_s ]) { |found, path| yield found, path }
60
+ end
61
+ end
62
+ end
63
+ end
64
+
65
+ # V8: a Ref names a resource, a parameter or a pseudo-parameter of the stack; in
66
+ # Conditions and in Rules, a parameter or a pseudo-parameter.
67
+ #
68
+ # The CDK: "Element used in Ref expression with logical ID: 'DoesNotExist' not
69
+ # found" (cfn-parse.ts), where its finder answers resources and parameters and
70
+ # specialCaseRefs lists the pseudo-parameters; in Conditions the finder answers
71
+ # parameters alone. The engine: F1010, and F1020 for the target of a GetAtt.
72
+ class References < Rule
73
+ rule "V8"
74
+
75
+ def call(context)
76
+ names = Template::Names.new(context.template)
77
+ issues = []
78
+ Sites.each(context) do |value, at, parameters_only|
79
+ next unless Template.function?(value, "Ref")
80
+
81
+ target = value["Ref"]
82
+ next unless target.is_a?(String)
83
+ next if Template.pseudo_parameter?(target) || names.parameter?(target) || (!parameters_only && names.resource?(target))
84
+
85
+ issues << error(at, "Ref names #{target.inspect}, which is not #{reachable(parameters_only)} of this stack",
86
+ hint: parameters_only ? "a condition reaches parameters and pseudo-parameters only, by Ref" : "check the logical ID, or declare it")
87
+ end
88
+ issues
89
+ end
90
+
91
+ private
92
+
93
+ def reachable(parameters_only)
94
+ parameters_only ? "a parameter or a pseudo-parameter" : "a resource, a parameter or a pseudo-parameter"
95
+ end
96
+ end
97
+
98
+ # V9: the attribute of an Fn::GetAtt is one the type returns. The model is silent
99
+ # where its sources are: a type with no attribute listed is not checked, nor are the
100
+ # types whose attributes are open (the nested stack returns Outputs.<name>), nor a
101
+ # custom resource, whose attributes its own function decides. Those are the
102
+ # exemptions of the CDK's engine (intrinsics.rs, E9004 and getatt_attr_is_map_member).
103
+ #
104
+ # KNOWN_ATTRIBUTES holds what the corpus proves the model short of: Version, which
105
+ # CloudFormation returns for the two ImageBuilder recipes and the schemas do not
106
+ # list (two templates of the sample read it and deployed). The CDK's engine keeps
107
+ # the same kind of list, handwritten, where its data falls short
108
+ # (aws-cloudformation/cloudformation-validate@55ff54b6,
109
+ # src/data-source/handwritten/getatt_return_type_overrides.json).
110
+ #
111
+ # A resource the GetAtt names that is not there is rule V8's, as in the CDK: "Resource
112
+ # used in GetAtt expression with logical ID: 'DoesNotExist' not found".
113
+ class Attributes < Rule
114
+ rule "V9"
115
+
116
+ OPEN = %w[AWS::CloudFormation::Stack AWS::CloudFormation::Macro].freeze
117
+ KNOWN_ATTRIBUTES = {
118
+ "AWS::ImageBuilder::ContainerRecipe" => %w[Version],
119
+ "AWS::ImageBuilder::ImageRecipe" => %w[Version]
120
+ }.freeze
121
+ LISTED = 12
122
+
123
+ def call(context)
124
+ names = Template::Names.new(context.template)
125
+ issues = []
126
+ Sites.each(context) do |value, at, _parameters_only|
127
+ next unless Template.function?(value, "Fn::GetAtt")
128
+
129
+ target, attribute = Template.get_att(value["Fn::GetAtt"])
130
+ next unless target && attribute
131
+
132
+ unless names.resource?(target)
133
+ issues << error(at, "Fn::GetAtt names #{target.inspect}, which is not a resource of this stack",
134
+ hint: names.parameter?(target) ? "an attribute is read from a resource; a parameter is Ref'd" : "check the logical ID")
135
+ next
136
+ end
137
+ type = Template.resource_type(names.body(target))
138
+ next if type.nil? || custom?(type) || OPEN.include?(type)
139
+
140
+ schema = Schema.type(type)
141
+ next unless schema && !schema.read_only.empty?
142
+ next if Template.attribute?(schema.read_only, attribute)
143
+ next if KNOWN_ATTRIBUTES.fetch(type, []).include?(attribute)
144
+
145
+ issues << error(at, "#{attribute.inspect} is not an attribute AWS returns for #{type}; the attributes are #{listed(schema.read_only)}",
146
+ hint: schema.documentation_url ? "see #{schema.documentation_url}" : "check the attribute's name")
147
+ end
148
+ issues
149
+ end
150
+
151
+ private
152
+
153
+ def custom?(type)
154
+ type == "AWS::CloudFormation::CustomResource" || type.start_with?("Custom::")
155
+ end
156
+
157
+ def listed(attributes)
158
+ Text.list(attributes.first(LISTED)) + (attributes.size > LISTED ? ", and more" : "")
159
+ end
160
+ end
161
+
162
+ # V10: a variable of an Fn::Sub names a logical ID or has a value supplied in the
163
+ # Fn::Sub's own map. "${Id.Attribute}" reads an attribute of the resource Id.
164
+ #
165
+ # The CDK (cfn-parse.ts, parseFnSubString): the map is looked at first, then a
166
+ # pseudo-parameter, then, for a name with a dot, a resource, and without one a
167
+ # parameter or a resource: "Element referenced in Fn::Sub expression with logical
168
+ # ID: 'AFakeResource' was not found in the template". The engine: F1018.
169
+ class Substitutions < Rule
170
+ rule "V10"
171
+
172
+ def call(context)
173
+ names = Template::Names.new(context.template)
174
+ issues = []
175
+ Sites.each(context) do |value, at, _parameters_only|
176
+ next unless Template.function?(value, "Fn::Sub")
177
+
178
+ string, supplied = parts(value["Fn::Sub"])
179
+ next unless string
180
+
181
+ Template.variables(string) do |name|
182
+ next if name.empty? || supplied.key?(name) || reachable?(names, name)
183
+
184
+ issues << error(at, "#{name.inspect} in the Fn::Sub names no resource, parameter or pseudo-parameter of this stack, " \
185
+ "and the Fn::Sub supplies no value for it",
186
+ hint: "add it to the map of the Fn::Sub, as Fn.sub(string, #{name.inspect} => value)")
187
+ end
188
+ end
189
+ issues
190
+ end
191
+
192
+ private
193
+
194
+ # [ the string, the supplied values by name ] of an Fn::Sub, or [ nil, nil ] for
195
+ # one of another shape, which no rule here is about.
196
+ def parts(argument)
197
+ return [ argument, {} ] if argument.is_a?(String)
198
+ return [ argument[0], argument[1] ] if argument.is_a?(Array) && argument.size == 2 && argument[0].is_a?(String) && argument[1].is_a?(Hash)
199
+
200
+ [ nil, nil ]
201
+ end
202
+
203
+ def reachable?(names, name)
204
+ dot = name.index(".")
205
+ target = dot ? name[0, dot] : name
206
+ return true if Template.pseudo_parameter?(target) || names.parameter?(target) || names.resource?(target)
207
+
208
+ !dot && name.include?("::")
209
+ end
210
+ end
211
+
212
+ # V11: what DependsOn and Condition name exists. DependsOn names resources; the
213
+ # Condition of a resource and of an output, the condition of an Fn::If and of a
214
+ # "Condition" inside Conditions, and the mapping of an Fn::FindInMap, exist.
215
+ #
216
+ # The CDK (cfn-parse.ts): "Resource 'Bucket2' depends on 'Bucket1' that doesn't
217
+ # exist", "Resource 'Bucket' uses Condition 'AlwaysFalseCond' that doesn't exist",
218
+ # "Condition 'AlwaysFalse' used in an Fn::If expression does not exist in the
219
+ # template", "Referenced Condition with name 'AlwaysFalse' was not found in the
220
+ # template", "Mapping used in FindInMap expression with name 'NonExistentMapping' was
221
+ # not found in the template"; and cfn-include.ts for an output: "Output with name
222
+ # 'SomeOutput' refers to a Condition with name 'NonexistentCondition' which was not
223
+ # found in this template". The engine: E3005, E8002, E6005, E1028, E8007 and F1012.
224
+ class Targets < Rule
225
+ rule "V11"
226
+
227
+ def call(context)
228
+ names = Template::Names.new(context.template)
229
+ issues = depends_on(context.template, names)
230
+ issues.concat(condition_of_resources(context.template, names))
231
+ issues.concat(condition_of_outputs(context.template, names))
232
+ Sites.each(context) do |value, at, _parameters_only|
233
+ issues << inside(value, at, names)
234
+ end
235
+ issues.compact
236
+ end
237
+
238
+ private
239
+
240
+ def depends_on(template, names)
241
+ Template.resources(template).flat_map do |name, body|
242
+ next [] unless body.key?("DependsOn")
243
+
244
+ declared = body["DependsOn"]
245
+ list = declared.is_a?(Array) ? declared : [ declared ]
246
+ list.each_with_index.filter_map do |target, index|
247
+ at = [ "Resources", name.to_s, "DependsOn", *(declared.is_a?(Array) ? [ "[#{index}]" ] : []) ]
248
+ if !target.is_a?(String)
249
+ error(at, "DependsOn names #{Template.show(target)}: it takes the logical ID of a resource, or a list of them",
250
+ hint: "write the logical ID, as depends_on: \"Name\" or depends_on: [ \"A\", \"B\" ]")
251
+ elsif !names.resource?(target)
252
+ error(at, "the resource #{name} depends on #{target.inspect}, which is not a resource of this stack",
253
+ hint: names.parameter?(target) ? "DependsOn reaches resources only; a parameter needs no dependency" : "check the logical ID")
254
+ end
255
+ end
256
+ end
257
+ end
258
+
259
+ def condition_of_resources(template, names)
260
+ Template.resources(template).filter_map do |name, body|
261
+ next unless body.key?("Condition")
262
+
263
+ no_condition([ "Resources", name.to_s, "Condition" ], names, body["Condition"], "used by the resource #{name}")
264
+ end
265
+ end
266
+
267
+ def condition_of_outputs(template, names)
268
+ Template.section(template, "Outputs").filter_map do |name, output|
269
+ next unless output.is_a?(Hash) && output.key?("Condition")
270
+
271
+ no_condition([ "Outputs", name.to_s, "Condition" ], names, output["Condition"], "referred to by the output #{name}")
272
+ end
273
+ end
274
+
275
+ # nil when the condition exists, or is an intrinsic whose value is not known here.
276
+ def no_condition(at, names, condition, where)
277
+ return if condition.is_a?(String) && names.condition?(condition)
278
+ return if !condition.is_a?(String) && Template.intrinsic?(condition)
279
+
280
+ error(at, "the condition #{Template.show(condition)}, #{where}, is not declared in the Conditions section",
281
+ hint: "declare it with condition(name, Fn.equals(...))")
282
+ end
283
+
284
+ # An Fn::If's condition, a "Condition" inside Conditions, or an Fn::FindInMap's mapping.
285
+ def inside(value, at, names)
286
+ if Template.function?(value, "Fn::If") && value["Fn::If"].is_a?(Array) && value["Fn::If"][0].is_a?(String)
287
+ no_condition(at + [ "Fn::If", "[0]" ], names, value["Fn::If"][0], "used in an Fn::If")
288
+ elsif at.first == "Conditions" && Template.function?(value, "Condition") && value["Condition"].is_a?(String)
289
+ no_condition(at, names, value["Condition"], "referenced from the Conditions section")
290
+ elsif Template.function?(value, "Fn::FindInMap") && value["Fn::FindInMap"].is_a?(Array) && value["Fn::FindInMap"][0].is_a?(String)
291
+ mapping = value["Fn::FindInMap"][0]
292
+ unless names.mapping?(mapping)
293
+ error(at, "the Fn::FindInMap names the mapping #{mapping.inspect}, which the template does not declare",
294
+ hint: "declare it with mapping(#{mapping.inspect}, ...)")
295
+ end
296
+ end
297
+ end
298
+ end
299
+ # V14: no cycle through Ref, Fn::GetAtt, Fn::Sub and DependsOn between resources.
300
+ #
301
+ # The CDK (cfn-include.ts, getOrCreateResource): "Found a cycle between resources in
302
+ # the template: Bucket1 depends on Bucket2 depends on Bucket1". It follows the
303
+ # references inside a resource's properties first and its DependsOn last, and it
304
+ # stops at the first cycle; this walks in the same order and answers every cycle it
305
+ # meets. The engine: F3004.
306
+ class Cycles < Rule
307
+ rule "V14"
308
+
309
+ def call(context)
310
+ resources = Template.resources(context.template)
311
+ names = resources.keys.map(&:to_s)
312
+ edges = resources.to_h { |name, body| [ name.to_s, targets(body, names) ] }
313
+ issues = []
314
+ explored = {}
315
+ edges.each_key do |start|
316
+ next if explored[start]
317
+
318
+ found = {}
319
+ follow(start, [], {}, edges, explored, found)
320
+ found.each_value do |chain, root|
321
+ issues << error([ "Resources", root ], "Found a cycle between resources in the template: #{chain.join(" depends on ")}",
322
+ hint: "a resource cannot depend on one that depends on it: break the circle with an Fn::GetAtt, or restructure")
323
+ end
324
+ end
325
+ issues
326
+ end
327
+
328
+ private
329
+
330
+ # The resources a resource refers to, in the order the CDK reads them: those of its
331
+ # properties first, then those of every other attribute, and what DependsOn names,
332
+ # which may be one logical ID or a list of them. A plain string elsewhere is
333
+ # data, not a reference: a policy whose PolicyName happens to be its own logical
334
+ # ID is no cycle, and the corpus has one.
335
+ def targets(body, names)
336
+ properties = body["Properties"]
337
+ properties = properties.reject { |key, _| key == "TemplateBody" } if body["Type"] == Sites::NESTED_STACK && properties.is_a?(Hash)
338
+ depended = Array(body["DependsOn"]).select { |id| names.include?(id) }
339
+ [ properties, body.reject { |attribute, _| attribute == "Properties" } ]
340
+ .flat_map { |part| referred(part, names, []) }
341
+ .concat(depended)
342
+ end
343
+
344
+ def referred(value, names, found)
345
+ case value
346
+ when Hash
347
+ reference(value, names, found) || value.each_value { |item| referred(item, names, found) }
348
+ when Array
349
+ value.each { |item| referred(item, names, found) }
350
+ end
351
+ found
352
+ end
353
+
354
+ # True when the value is an intrinsic that names resources.
355
+ def reference(value, names, found)
356
+ if Template.function?(value, "Ref")
357
+ found << value["Ref"] if names.include?(value["Ref"])
358
+ elsif Template.function?(value, "Fn::GetAtt")
359
+ target, = Template.get_att(value["Fn::GetAtt"])
360
+ found << target if target && names.include?(target)
361
+ elsif Template.function?(value, "Fn::Sub")
362
+ string, supplied = substitution(value["Fn::Sub"])
363
+ if string.is_a?(String)
364
+ Template.variables(string) { |name| record(name, supplied, names, found) }
365
+ end
366
+ else
367
+ return false
368
+ end
369
+ true
370
+ end
371
+
372
+ # Records the resource a variable of an Fn::Sub names, when it is one of this
373
+ # template's. "${Id.Attribute}" names the resource Id.
374
+ def record(name, supplied, names, found)
375
+ return if name.empty? || supplied.key?(name)
376
+
377
+ dot = name.index(".")
378
+ reached = dot ? String(name[0, dot]) : name
379
+ found << reached if names.include?(reached)
380
+ end
381
+
382
+ # [ the string, the names the Fn::Sub supplies itself ] of its argument.
383
+ def substitution(argument)
384
+ return [ argument, {} ] if argument.is_a?(String)
385
+ return [ nil, {} ] unless argument.is_a?(Array)
386
+
387
+ [ argument[0], argument[1].is_a?(Hash) ? argument[1] : {} ]
388
+ end
389
+
390
+ # Depth first from node. found gathers each cycle by the names it goes round, so
391
+ # that one met twice is answered once: [ the chain as the CDK writes it, the root ].
392
+ def follow(node, path, on_path, edges, explored, found)
393
+ explored[node] = true
394
+ on_path[node] = true
395
+ path << node
396
+ edges[node].each do |target|
397
+ if on_path[target]
398
+ cycle = path[path.index(target)..] + [ target ]
399
+ found[cycle.rotate(cycle.index(cycle.min))] ||= [ path + [ target ], path.first ]
400
+ elsif !explored[target]
401
+ follow(target, path, on_path, edges, explored, found)
402
+ end
403
+ end
404
+ path.pop
405
+ on_path.delete(node)
406
+ end
407
+ end
408
+
409
+ # V20: an Fn::Sub holds no empty "${}".
410
+ #
411
+ # The CDK refuses it as a name that is not in the template: "Element referenced in
412
+ # Fn::Sub expression with logical ID: '' was not found in the template"
413
+ # (cfn-parse.ts); architecture §6 gives it its own number.
414
+ class EmptySubstitution < Rule
415
+ rule "V20"
416
+
417
+ def call(context)
418
+ issues = []
419
+ Sites.each(context) do |value, at, _parameters_only|
420
+ next unless Template.function?(value, "Fn::Sub")
421
+
422
+ argument = value["Fn::Sub"]
423
+ string = argument.is_a?(Array) ? argument[0] : argument
424
+ next unless string.is_a?(String) && empty_variable?(string)
425
+
426
+ issues << error(at, "the Fn::Sub holds an empty variable, \"${}\"", hint: "name a logical ID, or supply a value in the map of the Fn::Sub")
427
+ end
428
+ issues
429
+ end
430
+
431
+ private
432
+
433
+ # True when one of the variables of the string is empty, "${}".
434
+ def empty_variable?(string)
435
+ Template.variables(string) { |name| return true if name.empty? }
436
+ false
437
+ end
438
+ end
439
+
440
+ # V21: a short-form Fn::GetAtt ("Id.Attribute") has both parts.
441
+ #
442
+ # The CDK: "Short-form Fn::GetAtt must contain a '.' in its string argument, got:
443
+ # 'Bucket1Arn'" (cfn-parse.ts).
444
+ class ShortFormGetAtt < Rule
445
+ rule "V21"
446
+
447
+ def call(context)
448
+ issues = []
449
+ Sites.each(context) do |value, at, _parameters_only|
450
+ next unless Template.function?(value, "Fn::GetAtt")
451
+
452
+ argument = value["Fn::GetAtt"]
453
+ if argument.is_a?(String)
454
+ next if argument.include?(".")
455
+
456
+ issues << error(at, "the short form of Fn::GetAtt must contain a \".\" in its string argument, got: #{argument.inspect}",
457
+ hint: 'write "LogicalId.Attribute"')
458
+ elsif argument.is_a?(Array)
459
+ next if argument.size == 2 && argument.all? { |part| part.is_a?(String) || Template.intrinsic?(part) }
460
+
461
+ issues << error(at, "Fn::GetAtt takes the logical ID of a resource and the name of one of its attributes",
462
+ hint: 'write [ "LogicalId", "Attribute" ]')
463
+ end
464
+ end
465
+ issues
466
+ end
467
+ end
468
+
469
+ # V22: no Fn::GetAtt in the Conditions section.
470
+ #
471
+ # The CDK: "Using GetAtt in Condition definitions is not allowed" (cfn-include.ts,
472
+ # the finder of getOrCreateCondition). The engine: E9101.
473
+ class NoGetAttInConditions < Rule
474
+ rule "V22"
475
+
476
+ def call(context)
477
+ issues = []
478
+ Template.walk(Template.section(context.template, "Conditions"), "Conditions") do |value, at|
479
+ next unless Template.function?(value, "Fn::GetAtt")
480
+
481
+ issues << error(at, "Fn::GetAtt is not allowed in the Conditions section",
482
+ hint: "a condition compares parameters and pseudo-parameters, with Ref and Fn::FindInMap")
483
+ end
484
+ issues
485
+ end
486
+ end
487
+ end
488
+ end
489
+ end