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,469 @@
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
+ # The rules over what a template says about its resources and its sections: their
10
+ # types, their properties and their values (architecture §6: V1 to V7, V12, V13 and
11
+ # V16 to V19). Each is a class, with its id, that answers the issues it finds.
12
+ module Rules
13
+ # V1: a resource type the model knows. One it does not know is a warning: its keys
14
+ # are written as given (the normalizer) and nothing else is checked of it. That is
15
+ # what lets a Custom::* resource, or one of a private registry, through; with
16
+ # strict_types it is an error. A resource with no type at all is always an error.
17
+ #
18
+ # The engine behind the CDK's own validation reports a type it does not know as
19
+ # F3006, and the CDK downgrades it to a warning unless asked to be strict
20
+ # (aws-cloudformation/cloudformation-validate@55ff54b6, src/rules/src/registry.rs;
21
+ # aws/aws-cdk@68b2516c, core/lib/private/synthesis-validation.ts,
22
+ # downgradeCfnValidateErrorsToWarnings).
23
+ class KnownTypes < Rule
24
+ rule "V1"
25
+
26
+ def initialize(strict_types: false)
27
+ @strict_types = strict_types
28
+ end
29
+
30
+ def call(context)
31
+ issues = []
32
+ Scans::Resources.each(context) do |name, body, path|
33
+ type = Template.resource_type(body)
34
+ if type.nil?
35
+ issues << error(path + [ "Type" ], "the resource #{name} has no Type",
36
+ hint: "every resource names its type, as \"AWS::S3::Bucket\"")
37
+ elsif !Schema.known_type?(type)
38
+ issues << unknown(path + [ "Type" ], type)
39
+ end
40
+ end
41
+ issues
42
+ end
43
+
44
+ private
45
+
46
+ def unknown(path, type)
47
+ message = "#{type.inspect} is not a resource type the schema model knows: its properties are written as you give them, " \
48
+ "and nothing else is checked of this resource"
49
+ near = Text.closest(type, Schema.types)
50
+ hint = +"check the spelling"
51
+ hint << "; did you mean #{Text.list(near)}?" unless near.empty?
52
+ hint << ". With --strict-types this is an error"
53
+ @strict_types ? error(path, message, hint:) : warning(path, message, hint:)
54
+ end
55
+ end
56
+
57
+ # V2: a logical ID holds letters and digits only, and a parameter and a resource
58
+ # never share one.
59
+ #
60
+ # The pipeline runs a V2 of its own from the tree (synth/rules.rb); this one is for a
61
+ # template with no tree behind it. It checks what the CDK's engine checks
62
+ # (aws-cloudformation/cloudformation-validate@55ff54b6, src/rules/src/registry.rs
63
+ # and src/cel-engine/src/rules/structure.rs): the characters, under F0006, F2003,
64
+ # F6004 and E7001, and the one clash CloudFormation refuses, a parameter and a
65
+ # resource of one name, under F3007. A condition and a resource may share a name,
66
+ # and so may an output and a resource: the CDK's own include tests synthesize both
67
+ # (aws/aws-cdk@68b2516c, cloudformation-include/test/test-templates/
68
+ # condition-same-name-as-resource.json and outputs-with-references.json).
69
+ class LogicalIds < Rule
70
+ rule "V2"
71
+
72
+ PATTERN = /\A[A-Za-z0-9]+\z/
73
+ SECTIONS = %w[Parameters Mappings Conditions Resources Outputs].freeze
74
+
75
+ def call(context)
76
+ template = context.template
77
+ return [] unless template.is_a?(Hash)
78
+
79
+ issues = SECTIONS.flat_map do |section|
80
+ Template.section(template, section).keys.filter_map do |name|
81
+ next if name.to_s.match?(PATTERN)
82
+
83
+ error([ section, name.to_s ], "the logical ID #{name.inspect} must hold letters and digits only",
84
+ hint: "CloudFormation takes no \"_\", \"-\" or \".\" in a logical ID: write #{suggestion(name)}")
85
+ end
86
+ end
87
+ issues.concat(clashes(template))
88
+ end
89
+
90
+ private
91
+
92
+ # "my_table" as "MyTable", as the pipeline's V2 says it.
93
+ def suggestion(name)
94
+ name.to_s.split(/[^A-Za-z0-9]+/).map(&:capitalize).join
95
+ end
96
+
97
+ def clashes(template)
98
+ parameters = Template.section(template, "Parameters").keys.map(&:to_s)
99
+ Template.section(template, "Resources").keys.map(&:to_s).select { |name| parameters.include?(name) }.map do |name|
100
+ error([ "Resources", name ], "the logical ID #{name.inspect} is declared more than once in the stack: in Parameters.#{name} and here",
101
+ hint: "a logical ID names one thing in the whole stack")
102
+ end
103
+ end
104
+ end
105
+
106
+ # V3: a property exists on the type. What the normalizer could not resolve is still
107
+ # written as it was; this is the one place that says so, with the closest names. A
108
+ # type that takes properties it does not list (AWS::CloudFormation::CustomResource)
109
+ # and a value the model stops at (a policy document) are not checked.
110
+ #
111
+ # F3002 of the CDK's engine: additional properties are not allowed.
112
+ class Properties < Rule
113
+ rule "V3"
114
+
115
+ def call(context)
116
+ issues = []
117
+ Scans::Keys.unresolved(context) do |key, outcome, names, at, owner|
118
+ next unless outcome == :none
119
+
120
+ near = Text.closest(key, names)
121
+ message = "#{key.inspect} is not a property of #{owner}"
122
+ message << "; did you mean #{Text.list(near)}?" unless near.empty?
123
+ hint = if near.empty? && names.size <= 12
124
+ "its properties are #{Text.list(names)}"
125
+ else
126
+ "write the CloudFormation name, or in snake_case: #{Text.list(near.map { |name| Template.snake(name) })}"
127
+ end
128
+ issues << error(at, message, hint:)
129
+ end
130
+ issues
131
+ end
132
+ end
133
+
134
+ # V4: a key names one property. It is written as it was when, read without regard to
135
+ # case and underscores, it could be more than one of them.
136
+ class AmbiguousProperties < Rule
137
+ rule "V4"
138
+
139
+ def call(context)
140
+ issues = []
141
+ Scans::Keys.unresolved(context) do |key, outcome, names, at, owner|
142
+ next unless outcome == :ambiguous
143
+
144
+ matches = names.select { |name| Template.fold(name) == Template.fold(key) }
145
+ issues << error(at, "#{key.inspect} could name #{Text.list(matches)} of #{owner}",
146
+ hint: "write the CloudFormation name of the one you mean")
147
+ end
148
+ issues
149
+ end
150
+ end
151
+
152
+ # V5: the properties a type lists as required are there, at every level the model
153
+ # describes. A nil is absent, an Fn::If is present, and so is a property the
154
+ # template sets even where the model says nothing may be read from it.
155
+ #
156
+ # The messages follow the CDK's own validators: a missing property at the top is
157
+ # "is missing required property: name", one inside a list is "name: required but
158
+ # missing" (packages/aws-cdk-lib/core/lib/runtime.ts, requireProperty and
159
+ # requiredValidator, at aws/aws-cdk@68b2516c).
160
+ #
161
+ # EXEMPTED holds what the corpus proves the sources wrong about: the provider
162
+ # schema of AWS::CloudFormation::Stack requires StackName, and every nested stack
163
+ # the CDK synthesizes (four templates of the sample have one) has no StackName and
164
+ # deploys. Nothing else was exempted.
165
+ class Required < Rule
166
+ rule "V5"
167
+
168
+ EXEMPTED = { "AWS::CloudFormation::Stack" => %w[StackName] }.freeze
169
+
170
+ def call(context)
171
+ issues = []
172
+ Scans::Resources.typed(context) do |_name, _body, path, type, properties|
173
+ skipped = EXEMPTED.fetch(type.name, [])
174
+ SchemaWalk.each_node(type, properties, path) do |walk_type, node, hash, at|
175
+ node.required.each do |required|
176
+ next if skipped.include?(required) && walk_type.equal?(type)
177
+ next if walk_type.read_only.include?(required) || present?(hash, node, required)
178
+
179
+ issues << missing(at + [ required ], required, Template.node_name(walk_type, node))
180
+ end
181
+ end
182
+ SchemaWalk.each_value(type, properties, path) do |walk_type, _node, property, value, at|
183
+ SchemaWalk.each_nil_element(walk_type, property, value, at) do |definition, element|
184
+ definition.required.each do |required|
185
+ issues << missing(element + [ required ], required, Template.node_name(walk_type, definition))
186
+ end
187
+ end
188
+ end
189
+ end
190
+ issues
191
+ end
192
+
193
+ private
194
+
195
+ def present?(hash, node, name)
196
+ hash.any? { |key, value| !value.nil? && Normalizer.lookup(node, key.to_s)&.name == name }
197
+ end
198
+
199
+ def missing(path, name, owner)
200
+ error(path, "the required property #{name} is missing on #{owner}", hint: "add it, as #{name} or in snake_case as #{Template.snake(name)}")
201
+ end
202
+ end
203
+
204
+ # V6: a literal has the kind of its property. A number or a boolean in quotes is
205
+ # rule V17's, and a list that is not an array is rule V7's. An intrinsic is never
206
+ # wrong: it stands for a value only CloudFormation will know.
207
+ #
208
+ # F3012 of the CDK's engine: property type mismatch.
209
+ class Kinds < Rule
210
+ rule "V6"
211
+
212
+ def call(context)
213
+ issues = []
214
+ Scans::Leaves.each(context) do |_type, _node, property, kind, value, at|
215
+ next if kind == :list || Scans::Kind.check(kind, value) != :wrong
216
+
217
+ issues << error(at, "#{Template.show(value)} is written where #{Scans::Kind.article(kind)} is expected (#{property.name})",
218
+ hint: Scans::Kind.hint(kind))
219
+ end
220
+ issues
221
+ end
222
+ end
223
+
224
+ # V7: a list property holds an array. Where the type allows each element once, an
225
+ # element written twice is a warning.
226
+ #
227
+ # The CDK's own validator says `"CorsRules!" should be a list` (core/lib/runtime.ts,
228
+ # listValidator); F3037 and W9007 of its engine cover duplicates.
229
+ class Lists < Rule
230
+ rule "V7"
231
+
232
+ def call(context)
233
+ issues = []
234
+ Scans::Leaves.each(context) do |type, node, property, kind, value, at|
235
+ next unless kind == :list
236
+
237
+ if value.is_a?(Array)
238
+ next unless property.unique_items == true
239
+
240
+ duplicates(value).each do |item, count|
241
+ issues << warning(at, "#{Template.show(item)} is written #{count} times in #{property.name}, which takes each value once",
242
+ hint: "remove the duplicates: AWS rejects this list")
243
+ end
244
+ else
245
+ issues << error(at, "#{Template.show(value)} is written where a list is expected (#{Template.node_name(type, node)}.#{property.name})",
246
+ hint: "write an Array, as [ \"GET\", \"POST\" ]")
247
+ end
248
+ end
249
+ issues
250
+ end
251
+
252
+ private
253
+
254
+ # [ item, how often ] for every literal and every object written more than once,
255
+ # in the order of their first appearance. Intrinsics are left out.
256
+ def duplicates(list)
257
+ seen = Hash.new(0)
258
+ list.each { |item| seen[item] += 1 unless Template.intrinsic?(item) }
259
+ seen.select { |_item, count| count > 1 }.to_a
260
+ end
261
+ end
262
+
263
+ # V12: the quotas of a template, and the lengths of its names.
264
+ #
265
+ # The numbers are the CDK's engine's (aws-cloudformation/cloudformation-validate@
266
+ # 55ff54b6, src/cel-engine/src/rules/structure.rs: F0007, F0003, F0004, F0008 and
267
+ # F0009 for the counts; F2011, F6011 and F7002 for 255 characters; F0011 for the
268
+ # Description). Two differences, both from architecture §6: the Description is
269
+ # measured in bytes, as AWS states the quota and as §6 says, where the engine counts
270
+ # characters; and the 255 apply to the names of conditions and of resources too.
271
+ class Quotas < Rule
272
+ rule "V12"
273
+
274
+ LIMITS = { "Resources" => 500, "Parameters" => 200, "Outputs" => 200, "Mappings" => 200, "Conditions" => 200 }.freeze
275
+ NAMED = %w[Parameters Mappings Conditions Resources Outputs].freeze
276
+ NAME_LENGTH = 255
277
+ DESCRIPTION_BYTES = 1024
278
+
279
+ def call(context)
280
+ template = context.template
281
+ return [] unless template.is_a?(Hash)
282
+
283
+ issues = LIMITS.filter_map do |section, limit|
284
+ count = Template.section(template, section).size
285
+ next unless count > limit
286
+
287
+ error([ section ], "the template declares #{count} #{section.downcase}, and CloudFormation accepts at most #{limit} of them",
288
+ hint: "split the stack")
289
+ end
290
+ NAMED.each do |section|
291
+ Template.section(template, section).each_key do |name|
292
+ next unless name.to_s.length > NAME_LENGTH
293
+
294
+ issues << error([ section, name.to_s ], "the logical ID is #{name.to_s.length} characters long; CloudFormation accepts at most #{NAME_LENGTH}",
295
+ hint: "shorten it")
296
+ end
297
+ end
298
+ description = template["Description"]
299
+ if description.is_a?(String) && description.bytesize > DESCRIPTION_BYTES
300
+ issues << error([ "Description" ], "the Description is #{description.bytesize} bytes long; CloudFormation accepts at most #{DESCRIPTION_BYTES}",
301
+ hint: "shorten it, and put the rest where a reader will find it")
302
+ end
303
+ issues
304
+ end
305
+ end
306
+
307
+ # V13: a stack name starts with a letter, goes on with letters, digits and hyphens,
308
+ # and is at most 128 characters long. The pipeline runs its own V13 from the tree
309
+ # (synth/rules.rb, over Core::Stack::NAME_PATTERN, which this is a copy of: core is
310
+ # not a dependency of the validation component). A template with no stack behind it
311
+ # has nothing to check.
312
+ class StackName < Rule
313
+ rule "V13"
314
+
315
+ NAME = /\A[A-Za-z][A-Za-z0-9-]*\z/
316
+ MAX_NAME_LENGTH = 128
317
+
318
+ def call(context)
319
+ stack = context.stack
320
+ name = stack.respond_to?(:stack_name) ? stack.stack_name : nil
321
+ return [] if name.nil? || (name.is_a?(String) && name.match?(NAME) && name.length <= MAX_NAME_LENGTH)
322
+
323
+ [
324
+ error("Stack", "the stack name #{name.inspect} is not valid: it must start with a letter, go on with letters, digits and hyphens, " \
325
+ "and be at most #{MAX_NAME_LENGTH} characters long",
326
+ hint: "a stack's name is the prefix of App.new(stack_name_prefix:) followed by its id")
327
+ ]
328
+ end
329
+ end
330
+
331
+ # V16: DeletionPolicy is one of Delete, Retain, RetainExceptOnCreate and Snapshot;
332
+ # UpdateReplacePolicy is one of Delete, Retain and Snapshot. An intrinsic may stand
333
+ # for a policy, as the CDK's include accepts (test-templates/intrinsic-deletion-
334
+ # policy.json and intrinsic-deletion-policy-ref.json); the literal branches of an
335
+ # Fn::If are each checked, as the engine checks every scenario a policy can take.
336
+ #
337
+ # F3016 and F0018 of the CDK's engine.
338
+ class Policies < Rule
339
+ rule "V16"
340
+
341
+ ALLOWED = { "DeletionPolicy" => %w[Delete Retain RetainExceptOnCreate Snapshot], "UpdateReplacePolicy" => %w[Delete Retain Snapshot] }.freeze
342
+
343
+ def call(context)
344
+ issues = []
345
+ Scans::Resources.each(context) do |_name, body, path|
346
+ ALLOWED.each do |attribute, allowed|
347
+ next unless body.key?(attribute)
348
+
349
+ wrong(body[attribute], allowed, []) do |value, at|
350
+ issues << error(path + [ attribute, *at ], "#{attribute} #{Template.show(value)} is not one of #{Text.list(allowed)}",
351
+ hint: attribute == "UpdateReplacePolicy" ? "CloudFormation takes no RetainExceptOnCreate here: write Retain" : "write the name as it is, or pass deletion_policy: as a symbol")
352
+ end
353
+ end
354
+ end
355
+ issues
356
+ end
357
+
358
+ private
359
+
360
+ # Yields each literal a policy attribute holds that CloudFormation takes no, with
361
+ # the segments that lead to it inside an Fn::If. An intrinsic that is no Fn::If
362
+ # yields nothing: what it resolves to is not known here.
363
+ def wrong(value, allowed, at)
364
+ if Template.function?(value, "Fn::If") && value["Fn::If"].is_a?(Array) && value["Fn::If"].size == 3
365
+ value["Fn::If"][1, 2].each_with_index do |branch, index|
366
+ wrong(branch, allowed, at + [ "Fn::If", "[#{index + 1}]" ]) { |found, where| yield found, where }
367
+ end
368
+ elsif !Template.intrinsic?(value) && !(value.is_a?(String) && allowed.include?(value))
369
+ yield value, at
370
+ end
371
+ end
372
+ end
373
+
374
+ # V17: a number or a boolean written as a string, where the schema says a number or
375
+ # a boolean. The CDK's include accepts it and converts it (cloudformation-include/
376
+ # test/valid-templates.test.ts: "accepts strings for properties with type number");
377
+ # here it is an error with the hint, by architecture §21.
378
+ class QuotedValues < Rule
379
+ rule "V17"
380
+
381
+ def call(context)
382
+ issues = []
383
+ Scans::Leaves.each(context) do |_type, _node, property, kind, value, at|
384
+ outcome = Scans::Kind.check(kind, value)
385
+ next unless outcome == :string_for_number || outcome == :string_for_boolean
386
+
387
+ hint = outcome == :string_for_number ? "drop the quotes: write #{value.strip}" : "drop the quotes: write #{value}"
388
+ issues << error(at, "#{Template.show(value)} is written where #{Scans::Kind.article(kind)} is expected (#{property.name})", hint:)
389
+ end
390
+ issues
391
+ end
392
+ end
393
+
394
+ # V18: a literal string is among the values the source lists for the property, in a
395
+ # list or a map element as much as at the top. A number or a boolean is not
396
+ # checked: CloudFormation takes it as its text, as the CDK's include does
397
+ # (test-templates/boolean-for-string.json and number-for-string.json are in its
398
+ # valid set).
399
+ #
400
+ # W3030 of the CDK's engine (a warning there; an error here, by architecture §6).
401
+ class AllowedValues < Rule
402
+ rule "V18"
403
+
404
+ STRUCTURAL = %i[list map nested json].freeze
405
+
406
+ def call(context)
407
+ issues = []
408
+ Scans::Leaves.each(context) do |_type, _node, property, kind, value, at|
409
+ values = property.allowed_values
410
+ next if values.nil? || values.empty? || STRUCTURAL.include?(kind) || !value.is_a?(String)
411
+ next unless Scans::Kind.check(kind, value) == :ok
412
+ next if values.include?(value)
413
+
414
+ issues << error(at, "#{Template.show(value)} is not one of the values #{property.name} takes: #{Text.list(values)}",
415
+ hint: "write one of them, exactly as AWS spells it")
416
+ end
417
+ issues
418
+ end
419
+ end
420
+
421
+ # V19: a literal string matches the pattern the source has for the property. A
422
+ # pattern is not anchored by JSON Schema, and is not here. A pattern Ruby cannot
423
+ # read is not checked.
424
+ #
425
+ # F3031 of the CDK's engine (fatal there; a warning here, by architecture §6).
426
+ class Patterns < Rule
427
+ rule "V19"
428
+
429
+ # The patterns of the model, compiled once: a Regexp, or false for one Ruby cannot read.
430
+ COMPILED = {}
431
+
432
+ def call(context)
433
+ issues = []
434
+ Scans::Leaves.each(context) do |type, _node, property, kind, value, at|
435
+ next unless kind == :string && value.is_a?(String) && property.pattern
436
+
437
+ regex = compiled(property.pattern)
438
+ next if !regex || regex.match?(value)
439
+
440
+ issues << warning(at, "#{Template.show(value)} does not match the pattern #{property.name} is documented with: #{property.pattern}",
441
+ hint: type.documentation_url ? "see #{type.documentation_url}" : "check the value against the documentation of the type")
442
+ end
443
+ issues
444
+ end
445
+
446
+ private
447
+
448
+ def compiled(pattern)
449
+ COMPILED.fetch(pattern) { COMPILED[pattern] = readable(pattern) }
450
+ end
451
+
452
+ # The source's patterns are JavaScript's; a few use syntax Ruby has no reading of.
453
+ # Ruby warns on each compile about the `-` AWS leaves unescaped inside character
454
+ # classes — the pattern is theirs, so the warning is silenced here, once, and
455
+ # the rule's own reading of a pattern it cannot compile is `false`.
456
+ def readable(pattern)
457
+ saved = $stderr
458
+ $stderr = File.open(File::NULL, "w")
459
+ Regexp.new(pattern)
460
+ rescue RegexpError, SyntaxError
461
+ false
462
+ ensure
463
+ $stderr.close unless $stderr.equal?(saved)
464
+ $stderr = saved
465
+ end
466
+ end
467
+ end
468
+ end
469
+ end
@@ -0,0 +1,203 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Validation
5
+ # The parts of a template the rules read, and the walks they share. Nothing here
6
+ # knows a rule: it is how a template says "Ref", where a value sits in it, and how
7
+ # to visit every value.
8
+ #
9
+ # What an intrinsic looks like was read in the CDK, at commit
10
+ # 68b2516c09791d78b199f30e455e4670dc9cde6d: packages/aws-cdk-lib/core/lib/private/
11
+ # cloudformation-lang.ts, isIntrinsic, and helpers-internal/cfn-parse.ts,
12
+ # looksLikeCfnIntrinsic. An object with the one key "Ref", or the one key "Fn::...":
13
+ # an object with more keys is data, whatever its keys are called.
14
+ module Template
15
+ # The top-level sections a template is made of (architecture §5).
16
+ SECTIONS = %w[AWSTemplateFormatVersion Description Parameters Mappings Conditions Resources Outputs Metadata].freeze
17
+
18
+ # The sections whose values may hold no reference: CloudFormation takes literals there.
19
+ LITERAL_SECTIONS = %w[AWSTemplateFormatVersion Description Parameters Mappings].freeze
20
+
21
+ # The sections where a Ref reaches a parameter or a pseudo-parameter and nothing
22
+ # else, as in the CDK (cfn-parse.ts: the finders of Conditions and of Rules answer
23
+ # parameters alone).
24
+ PARAMETERS_ONLY = %w[Conditions Rules].freeze
25
+
26
+ module_function
27
+
28
+ # An intrinsic as the template holds it: { "Ref" => "Name" } or { "Fn::..." => ... } and nothing else.
29
+ def intrinsic?(value)
30
+ return false unless value.is_a?(Hash) && value.size == 1
31
+
32
+ key = value.keys.first
33
+ key == "Ref" || (key.is_a?(String) && key.start_with?("Fn::"))
34
+ end
35
+
36
+ # True when value is the one intrinsic name: { name => ... }.
37
+ def function?(value, name)
38
+ value.is_a?(Hash) && value.size == 1 && value.key?(name)
39
+ end
40
+
41
+ # A String, a number, a boolean or nil: a value CloudFormation takes as it is written.
42
+ def literal?(value)
43
+ value.is_a?(String) || value.is_a?(Numeric) || value == true || value == false || value.nil?
44
+ end
45
+
46
+ # "Resources.Table.Properties.KeySchema[0].KeyType": the way the pipeline writes a
47
+ # path. A segment that starts with "[" is an index and follows the last name directly.
48
+ def path(segments)
49
+ segments.each_with_object(+"") do |segment, text|
50
+ segment = segment.to_s
51
+ next text << segment if segment.start_with?("[")
52
+
53
+ text << "." unless text.empty?
54
+ text << segment
55
+ end
56
+ end
57
+
58
+ # Yields [ value, segments ] for value and everything below it, in the order it is
59
+ # written.
60
+ def walk(value, segments = [], &block)
61
+ segments = Kernel.Array(segments)
62
+ block.call(value, segments)
63
+ case value
64
+ when Hash
65
+ value.each { |key, item| walk(item, segments + [ key.to_s ], &block) }
66
+ when Array
67
+ value.each_with_index { |item, index| walk(item, segments + [ "[#{index}]" ], &block) }
68
+ end
69
+ nil
70
+ end
71
+
72
+ # A section of the template, as a Hash: empty when the template does not have it
73
+ # or holds something else there.
74
+ def section(template, name)
75
+ template.is_a?(Hash) && template[name].is_a?(Hash) ? template[name] : {}
76
+ end
77
+
78
+ # { "Table" => { "Type" => ... }, ... }: the resources of the template, those whose body is an object.
79
+ def resources(template)
80
+ section(template, "Resources").select { |_name, body| body.is_a?(Hash) }
81
+ end
82
+
83
+ # The Type of a resource, or nil when the body does not give it as a string.
84
+ def resource_type(body)
85
+ type = body["Type"] if body.is_a?(Hash)
86
+ type.is_a?(String) ? type : nil
87
+ end
88
+
89
+ # The names that can be Ref'd or substituted: resources, parameters, and the
90
+ # pseudo-parameters. The list of pseudo-parameters is the CDK's engine's
91
+ # (aws-cloudformation/cloudformation-validate@55ff54b6, template-model/src/consts.rs,
92
+ # PSEUDO_PARAMETERS).
93
+ PSEUDO_PARAMETERS = %w[AWS::AccountId AWS::NotificationARNs AWS::NoValue AWS::Partition AWS::Region AWS::StackId AWS::StackName AWS::URLSuffix].freeze
94
+
95
+ # The key the normalizer matches a property by: neither case nor underscores count
96
+ # (architecture §6). "SSEAlgorithm" and "sse_algorithm" both give "ssealgorithm".
97
+ def fold(name)
98
+ name.downcase.delete("_")
99
+ end
100
+
101
+ # "KeySchema" as "key_schema", "KMSMasterKeyID" as "kms_master_key_id": the way a
102
+ # property is written in Ruby.
103
+ def snake(name)
104
+ name.gsub(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase
105
+ end
106
+
107
+ # The name of what a node describes, for a message: "AWS::DynamoDB::Table" for a
108
+ # type, "AWS::DynamoDB::Table.KeySchema" for a definition nested in it.
109
+ def node_name(type, node)
110
+ node.equal?(type) ? type.name : "#{type.name}.#{node.name}"
111
+ end
112
+
113
+ # A value the way a message shows it: as Ruby writes it, and short.
114
+ def show(value)
115
+ text = value.inspect
116
+ text.size > 60 ? "#{text[0, 57]}..." : text
117
+ end
118
+
119
+ def pseudo_parameter?(name)
120
+ PSEUDO_PARAMETERS.include?(name)
121
+ end
122
+
123
+ # The logical ID and the attribute of an Fn::GetAtt, from its string form
124
+ # "Id.Attribute" (the first dot separates them, the attribute may hold more) or its
125
+ # list form [ "Id", "Attribute" ]. [ nil, nil ] when neither reads: a string with no
126
+ # dot (rule V21 says so), or anything that is not two names.
127
+ def get_att(argument)
128
+ if argument.is_a?(String)
129
+ dot = argument.index(".")
130
+ dot ? [ argument[0, dot], argument[(dot + 1)..] ] : [ nil, nil ]
131
+ elsif argument.is_a?(Array) && argument.size == 2 && argument[0].is_a?(String) && argument[1].is_a?(String)
132
+ argument
133
+ else
134
+ [ nil, nil ]
135
+ end
136
+ end
137
+
138
+ # Yields each variable of the string of an Fn::Sub the way CloudFormation reads it:
139
+ # from "${" to the next "}", trimmed. "${!...}" is no variable but literal text.
140
+ # Read in the CDK (cfn-parse.ts, parseFnSubString, aws/aws-cdk@68b2516c), with its
141
+ # test fixtures: a "${" with no "}" after it is text too.
142
+ def variables(string)
143
+ position = string.index("${") || string.length
144
+ while (opening = string.index("${", position))
145
+ closing = string.index("}", opening + 2)
146
+ break unless closing
147
+
148
+ name = string[(opening + 2)...closing].strip
149
+ position = closing + 1
150
+ yield name unless name.start_with?("!")
151
+ end
152
+ end
153
+
154
+ # Whether an attribute is one a resource type returns from Fn::GetAtt. A read-only
155
+ # path covers what lies below it ("Outputs" covers "Outputs.Key", "Endpoint" covers
156
+ # "Endpoint.Address"), and a "*" in it is any one segment, as the schemas write them.
157
+ def attribute?(read_only, attribute)
158
+ read_only.any? do |known|
159
+ next true if known == attribute || attribute.start_with?("#{known}.")
160
+
161
+ pattern = known.split(".").map { |part| part == "*" ? "[^.]+" : Regexp.escape(part) }.join("\\.")
162
+ attribute.match?(/\A#{pattern}\z/)
163
+ end
164
+ end
165
+
166
+ # The names of a template that a reference can reach.
167
+ class Names
168
+ attr_reader :resources, :parameters, :conditions, :mappings
169
+
170
+ # resources and parameters: the logical IDs. conditions and mappings: their names.
171
+ def initialize(template)
172
+ @bodies = Template.resources(template)
173
+ @resources = @bodies.keys.map(&:to_s)
174
+ @parameters = Template.section(template, "Parameters").keys.map(&:to_s)
175
+ @conditions = Template.section(template, "Conditions").keys.map(&:to_s)
176
+ @mappings = Template.section(template, "Mappings").keys.map(&:to_s)
177
+ freeze
178
+ end
179
+
180
+ def resource?(name)
181
+ @resources.include?(name)
182
+ end
183
+
184
+ def parameter?(name)
185
+ @parameters.include?(name)
186
+ end
187
+
188
+ def condition?(name)
189
+ @conditions.include?(name)
190
+ end
191
+
192
+ def mapping?(name)
193
+ @mappings.include?(name)
194
+ end
195
+
196
+ # The body of a resource, or nil.
197
+ def body(name)
198
+ @bodies[name]
199
+ end
200
+ end
201
+ end
202
+ end
203
+ end