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,290 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Ported from the AWS CDK.
4
+ #
5
+ # Origin: packages/aws-cdk-lib/matching/lib/matcher.ts
6
+ # Commit: 025a6f67fec3d37a6ffdc6168f8a751a04918f66 (aws/aws-cdk, main)
7
+ # Licence: Apache-2.0
8
+ # Changed: camelCase to snake_case, and a few names to Ruby's idiom for a
9
+ # question: isMatcher(x) is Matcher.matcher?(x), the isSuccess getter is
10
+ # is_success?, hasFailed() is has_failed?; finished() keeps its name, it does
11
+ # something rather than ask. recordFailure takes its fields as keywords, which
12
+ # is how Ruby writes the object literal it takes there. MatchFailure and
13
+ # MatchCapture are Data. The functions nested in renderMismatch() are methods of
14
+ # Private::MismatchRenderer, which reads three fields that the CDK keeps
15
+ # private on MatchResult: failures_here, inner_match_failures and captures are
16
+ # readers here, marked internal. push() is kept, deprecated as there.
17
+
18
+ require_relative "private/error"
19
+ require_relative "private/js"
20
+
21
+ module RubyCdk
22
+ module Test
23
+ # Represents a matcher that can perform special data matching capabilities
24
+ # between a given pattern and a target.
25
+ class Matcher
26
+ # Whether the value is a Matcher.
27
+ def self.matcher?(value)
28
+ value.is_a?(Matcher)
29
+ end
30
+
31
+ # A name for the matcher. This is collected as part of the result and may be
32
+ # presented to the user.
33
+ def name
34
+ raise NotImplementedError
35
+ end
36
+
37
+ # Test whether a target matches the provided pattern. Every Matcher must
38
+ # implement this method. This method will be invoked by the assertions
39
+ # framework. Do not call this method directly.
40
+ #
41
+ # Returns a MatchResult whose failures are the match failures: none when the
42
+ # match succeeded.
43
+ def test(actual)
44
+ raise NotImplementedError
45
+ end
46
+ end
47
+
48
+ # Match failure details.
49
+ #
50
+ # matcher: the matcher that had the failure
51
+ # path: where in the target. [] for the root of the match tree,
52
+ # [ "/foo", "[5]" ] for the 5th index of the array under key "foo"
53
+ # message: what did not match
54
+ # cost: the cost of this particular mismatch: nil, counted as 1, unless given
55
+ MatchFailure = Data.define(:matcher, :path, :message, :cost)
56
+
57
+ # Information about a value captured during match: the Capture it belongs to,
58
+ # and the value.
59
+ MatchCapture = Data.define(:capture, :value)
60
+
61
+ # The result of Matcher#test.
62
+ class MatchResult
63
+ # The target for which this result was generated.
64
+ attr_reader :target
65
+
66
+ # The number of failures.
67
+ attr_reader :fail_count
68
+
69
+ # Internal to the engine, not part of the public API: the failures of this
70
+ # result by path, the results composed under this one by id, and the captures
71
+ # recorded here by Capture.
72
+ attr_reader :failures_here, :inner_match_failures, :captures
73
+
74
+ def initialize(target)
75
+ @target = target
76
+ @failures_here = {}
77
+ @inner_match_failures = {}
78
+ @captures = {}
79
+ @finalized = false
80
+ @has_failed = false
81
+ @fail_count = 0
82
+ @cost = 0
83
+ end
84
+
85
+ # Deprecated in the CDK and here: record_failure.
86
+ def push(matcher, path, message)
87
+ record_failure(matcher: matcher, path: path, message: message)
88
+ end
89
+
90
+ # Record a new failure into this result at a specific path.
91
+ def record_failure(matcher:, path:, message:, cost: nil)
92
+ fail_key = path.join(".")
93
+ (@failures_here[fail_key] ||= []) << MatchFailure.new(matcher: matcher, path: path, message: message, cost: cost)
94
+ @fail_count += 1
95
+ @cost += cost || 1
96
+ @has_failed = true
97
+ self
98
+ end
99
+
100
+ # Whether the match is a success.
101
+ def is_success?
102
+ !@has_failed
103
+ end
104
+
105
+ # Does the result contain any failures. If not, the result is a success.
106
+ def has_failed?
107
+ @has_failed
108
+ end
109
+
110
+ # The cost of the failures so far.
111
+ def fail_cost
112
+ @cost
113
+ end
114
+
115
+ # Compose the results of a previous match as a subtree.
116
+ #
117
+ # id: the id of the parent tree.
118
+ def compose(id, inner)
119
+ # Record inner failure
120
+ if inner.has_failed?
121
+ @has_failed = true
122
+ @fail_count += inner.fail_count
123
+ @cost += inner.fail_cost
124
+ @inner_match_failures[id] = inner
125
+ end
126
+
127
+ # Copy captures so we all finalize them together
128
+ inner.captures.each do |capture, values|
129
+ values.each { |value| record_capture(capture: capture, value: value) }
130
+ end
131
+ self
132
+ end
133
+
134
+ # Prepare the result to be analyzed. This API *must* be called prior to
135
+ # analyzing these results.
136
+ def finished
137
+ return self if @finalized
138
+
139
+ if @fail_count.zero?
140
+ @captures.each { |capture, values| capture._append_captures(values) }
141
+ end
142
+ @finalized = true
143
+ self
144
+ end
145
+
146
+ # Render the failed match in a presentable way.
147
+ #
148
+ # Prefer render_mismatch over this method. It is left for backwards
149
+ # compatibility for test suites that expect it, but render_mismatch will
150
+ # produce better output.
151
+ def to_human_strings
152
+ failures = []
153
+ collect_failures(self, [], failures)
154
+ failures.map do |failure|
155
+ location = failure.path.empty? ? "" : " at /#{failure.path.join("/")}"
156
+ "#{failure.message}#{location} (using #{failure.matcher.name} matcher)"
157
+ end
158
+ end
159
+
160
+ # Do a deep render of the match result, showing the structure mismatches in context.
161
+ def render_mismatch
162
+ Private::MismatchRenderer.new(self).render
163
+ end
164
+
165
+ # Record a capture against in this match result.
166
+ def record_capture(capture:, value:)
167
+ (@captures[capture] ||= []) << value
168
+ nil
169
+ end
170
+
171
+ private
172
+
173
+ def collect_failures(result, prefix, failures)
174
+ result.failures_here.each_value do |fails|
175
+ fails.each do |fail|
176
+ failures << MatchFailure.new(matcher: fail.matcher, message: fail.message, path: prefix + fail.path, cost: fail.cost)
177
+ end
178
+ end
179
+ result.inner_match_failures.each { |key, inner| collect_failures(inner, prefix + [ key ], failures) }
180
+ end
181
+ end
182
+
183
+ module Private
184
+ # The functions that the CDK nests inside MatchResult#renderMismatch(), as
185
+ # methods of the object that does the rendering.
186
+ class MismatchRenderer
187
+ def initialize(result)
188
+ @result = result
189
+ @parts = []
190
+ @indents = []
191
+ end
192
+
193
+ def render
194
+ return "<match>" unless @result.has_failed?
195
+
196
+ emit_failures(@result, "")
197
+ recurse(@result)
198
+ Js.move_markers_to_front(Js.trim_end(@parts.join))
199
+ end
200
+
201
+ private
202
+
203
+ def emit(text)
204
+ @parts << text.gsub("\n", "\n#{@indents.join}")
205
+ end
206
+
207
+ # The failures reported at a path, each on its own line, marked with !!.
208
+ def emit_failures(result, path, scrap = nil)
209
+ (result.failures_here[path] || []).each { |failure| emit("!! #{failure.message}\n") }
210
+ scrap&.delete(path)
211
+ end
212
+
213
+ def recurse(result)
214
+ # Failures that have been reported against this result that we did not print yet
215
+ remaining = result.failures_here.keys.reject { |key| key == "" }
216
+
217
+ if result.target.is_a?(Array)
218
+ @indents.push(" ")
219
+ emit("[\n")
220
+ result.target.each_with_index do |_, index|
221
+ emit(",\n") unless index.zero?
222
+
223
+ emit_failures(result, index.to_s, remaining)
224
+ inner = result.inner_match_failures[index.to_s]
225
+ if inner
226
+ # Report the top-level failures on the line before the content
227
+ emit_failures(inner, "")
228
+ recurse_comparing_values(inner, result.target[index])
229
+ else
230
+ emit(Js.render_abridged(result.target[index]))
231
+ end
232
+ end
233
+
234
+ emit_remaining(result, remaining)
235
+ @indents.pop
236
+ emit("\n]")
237
+ return
238
+ end
239
+
240
+ if Js.object?(result.target)
241
+ @indents.push(" ")
242
+ emit("{\n")
243
+ keys = (Js.object_keys(result.target) + remaining).uniq.sort
244
+
245
+ keys.each_with_index do |key, index|
246
+ emit(",\n") unless index.zero?
247
+
248
+ emit_failures(result, key, remaining)
249
+ inner = result.inner_match_failures[key]
250
+ if inner
251
+ # Report the top-level failures on the line before the content
252
+ emit_failures(inner, "")
253
+ emit("#{Js.jsonify(key)}: ")
254
+ recurse_comparing_values(inner, Js.get(result.target, key))
255
+ else
256
+ emit("#{Js.jsonify(key)}: ")
257
+ emit(Js.render_abridged(Js.get(result.target, key)))
258
+ end
259
+ end
260
+
261
+ emit_remaining(result, remaining)
262
+ @indents.pop
263
+ emit("\n}")
264
+ return
265
+ end
266
+
267
+ emit_remaining(result, remaining)
268
+ emit(Js.jsonify(result.target))
269
+ end
270
+
271
+ def emit_remaining(result, remaining)
272
+ emit("\n") if remaining.any?
273
+
274
+ remaining.each { |key| emit_failures(result, key) }
275
+ end
276
+
277
+ # Recurse to the inner matcher, but with a twist: when the match result's
278
+ # target is not the value given here, the matcher matched a transformation
279
+ # of that value (a parsed JSON string, for one), and both are rendered.
280
+ def recurse_comparing_values(inner, actual_value)
281
+ return recurse(inner) if Js.strict_equal?(inner.target, actual_value)
282
+
283
+ emit(Js.render_abridged(actual_value))
284
+ emit(" <*> ")
285
+ recurse(inner)
286
+ end
287
+ end
288
+ end
289
+ end
290
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Ported from the AWS CDK.
4
+ #
5
+ # Origin: packages/aws-cdk-lib/matching/lib/private/matchers/absent.ts
6
+ # Commit: 025a6f67fec3d37a6ffdc6168f8a751a04918f66 (aws/aws-cdk, main)
7
+ # Licence: Apache-2.0
8
+ # Changed: nothing in behaviour. Undefined is RubyCdk::Test::UNDEFINED.
9
+
10
+ require_relative "js"
11
+ require_relative "../matcher"
12
+
13
+ module RubyCdk
14
+ module Test
15
+ module Private
16
+ # The matcher behind Match.absent().
17
+ class AbsentMatch < Matcher
18
+ attr_reader :name
19
+
20
+ def initialize(name)
21
+ @name = name
22
+ end
23
+
24
+ def test(actual)
25
+ result = MatchResult.new(actual)
26
+ unless actual.equal?(UNDEFINED)
27
+ result.record_failure(matcher: self, path: [], message: "Received #{Js.string(actual)}, but key should be absent")
28
+ end
29
+ result
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Ported from the AWS CDK.
4
+ #
5
+ # Origin: packages/aws-cdk-lib/assertions/lib/private/conditions.ts
6
+ # Commit: 025a6f67fec3d37a6ffdc6168f8a751a04918f66 (aws/aws-cdk, main)
7
+ # Licence: Apache-2.0
8
+ # Changed: camelCase to snake_case, and nothing in behaviour. The functions are
9
+ # module functions of Private.
10
+
11
+ require_relative "js"
12
+ require_relative "section"
13
+
14
+ module RubyCdk
15
+ module Test
16
+ module Private
17
+ module_function
18
+
19
+ def find_conditions(template, logical_id, props = {})
20
+ result = match_section(filter_logical_id(conditions_of(template), logical_id), props)
21
+ return {} unless result.match
22
+
23
+ result.matches
24
+ end
25
+
26
+ def has_condition(template, logical_id, props)
27
+ result = match_section(filter_logical_id(conditions_of(template), logical_id), props)
28
+ return if result.match
29
+
30
+ format_section_match_failure("conditions with logicalId #{logical_id}", result)
31
+ end
32
+
33
+ def conditions_of(template)
34
+ section = Js.get(template, "Conditions")
35
+ Js.nullish?(section) ? {} : section
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Ported from the AWS CDK.
4
+ #
5
+ # Origin: packages/aws-cdk-lib/assertions/lib/private/cyclic.ts
6
+ # Commit: 025a6f67fec3d37a6ffdc6168f8a751a04918f66 (aws/aws-cdk, main)
7
+ # Licence: Apache-2.0
8
+ # Changed: camelCase to snake_case. A Set is a list without doubles, in the
9
+ # order of insertion, as there. The literal fragments of an Fn::Sub string,
10
+ # which carry no logical ID, are not collected. A resource that is not an object
11
+ # has no dependencies here, where JavaScript would throw.
12
+
13
+ require_relative "error"
14
+ require_relative "js"
15
+
16
+ module RubyCdk
17
+ module Test
18
+ module Private
19
+ module_function
20
+
21
+ # Check a template for cyclic dependencies.
22
+ #
23
+ # This will make sure that we don't happily validate templates in unit tests
24
+ # that wouldn't deploy to CloudFormation anyway.
25
+ def check_template_for_cyclic_dependencies(template)
26
+ resources = Js.get(template, "Resources")
27
+ resources = {} if Js.nullish?(resources)
28
+ logical_ids = Js.object_keys(resources)
29
+
30
+ dependencies = {}
31
+ Js.object_keys(resources).each do |logical_id|
32
+ dependencies[logical_id] = find_resource_dependencies(resources[logical_id]).select { |id| logical_ids.include?(id) }
33
+ end
34
+
35
+ # We will now progressively remove entries from the map of 'dependencies' that have
36
+ # 0 elements in them. If we can't do that anymore and the map isn't empty, we
37
+ # have a cyclic dependency.
38
+ until dependencies.empty?
39
+ free = dependencies.select { |_logical_id, deps| deps.empty? }.keys
40
+ if free.empty?
41
+ # Oops!
42
+ cycle = find_cycle(dependencies)
43
+
44
+ cycle_resources = cycle.to_h { |logical_id| [ logical_id, Js.get(resources, logical_id) ] }
45
+
46
+ Kernel.raise AssertionError,
47
+ "Template is undeployable, these resources have a dependency cycle: #{cycle.join(" -> ")}:\n\n#{Js.json(cycle_resources, 2)}"
48
+ end
49
+
50
+ free.each do |logical_id|
51
+ dependencies.each_value { |deps| deps.delete(logical_id) }
52
+ dependencies.delete(logical_id)
53
+ end
54
+ end
55
+ nil
56
+ end
57
+
58
+ def find_resource_dependencies(resource)
59
+ return [] unless resource.is_a?(Hash)
60
+
61
+ depends_on = Js.get(resource, "DependsOn")
62
+ depends_on = [] if Js.nullish?(depends_on)
63
+ declared = depends_on.is_a?(Array) ? depends_on : [ depends_on ]
64
+ (declared + find_expression_dependencies(Js.get(resource, "Properties"))).uniq
65
+ end
66
+
67
+ def find_expression_dependencies(value)
68
+ found = []
69
+ recurse_expression(value, found)
70
+ found
71
+ end
72
+
73
+ def recurse_expression(value, found)
74
+ return if Js.nullish?(value)
75
+
76
+ value.each { |element| recurse_expression(element, found) } if value.is_a?(Array)
77
+
78
+ if Js.object?(value)
79
+ entries = Js.entries(value)
80
+ keys = entries.map(&:first)
81
+ if keys.length == 1 && keys[0] == "Ref"
82
+ found << entries[0][1]
83
+ elsif keys.length == 1 && keys[0] == "Fn::GetAtt"
84
+ argument = entries[0][1]
85
+ found << argument[0] if argument.is_a?(Array) || argument.is_a?(String)
86
+ elsif keys.length == 1 && keys[0] == "Fn::Sub"
87
+ argument = entries[0][1]
88
+ pattern = argument.is_a?(Array) ? argument[0] : argument
89
+
90
+ # pattern should always be a string, but we've encountered some cases in which
91
+ # it isn't. Better safeguard.
92
+ found.concat(logical_ids_in_sub_string(pattern)) if pattern.is_a?(String)
93
+
94
+ context_dict = argument.is_a?(Array) ? argument[1] : nil
95
+ recurse_expression(context_dict, found) if Js.object?(context_dict)
96
+ else
97
+ entries.each { |_key, element| recurse_expression(element, found) }
98
+ end
99
+ end
100
+ nil
101
+ end
102
+
103
+ # Return the logical IDs found in an Fn::Sub string.
104
+ def logical_ids_in_sub_string(pattern)
105
+ analyze_sub_pattern(pattern).filter_map do |fragment|
106
+ fragment[0] == :literal ? nil : fragment[1]
107
+ end
108
+ end
109
+
110
+ # :ref and :getatt fragments carry a logical ID; :literal ones do not.
111
+ def analyze_sub_pattern(pattern)
112
+ text = "#{pattern}"
113
+ fragments = []
114
+
115
+ search_from = 0
116
+ while (placeholder_start = text.index("${", search_from))
117
+ if text[placeholder_start + 2] == "!" # "${!" means "don't actually substitute"
118
+ search_from = placeholder_start + 3
119
+ next
120
+ end
121
+
122
+ placeholder_end = text.index("}", placeholder_start + 2)
123
+ break if placeholder_end.nil?
124
+
125
+ placeholder = text[(placeholder_start + 2)...placeholder_end] || ""
126
+
127
+ if placeholder.include?(".")
128
+ logical_id, = placeholder.split(".")
129
+ fragments << [ :getatt, logical_id ]
130
+ else
131
+ fragments << [ :ref, placeholder ]
132
+ end
133
+
134
+ search_from = placeholder_end + 1
135
+ end
136
+
137
+ fragments
138
+ end
139
+
140
+ # Find cycles in a graph. Not the fastest, but effective and should be rare.
141
+ def find_cycle(deps)
142
+ deps.each_key do |node|
143
+ cycle = cycle_from(node, [ node ], deps)
144
+ return cycle if cycle
145
+ end
146
+ Kernel.raise AssertionError, "No cycle found. Assertion failure!"
147
+ end
148
+
149
+ def cycle_from(node, path, deps)
150
+ (deps[node] || []).each do |dependency|
151
+ return path + [ dependency ] if path.include?(dependency)
152
+
153
+ cycle = cycle_from(dependency, path + [ dependency ], deps)
154
+ return cycle if cycle
155
+ end
156
+ nil
157
+ end
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Ported from the AWS CDK.
4
+ #
5
+ # Origin: packages/aws-cdk-lib/matching/lib/private/error.ts
6
+ # Commit: 025a6f67fec3d37a6ffdc6168f8a751a04918f66 (aws/aws-cdk, main)
7
+ # Licence: Apache-2.0
8
+ # Changed: the parent class. There it is Error. Here it is decided when this
9
+ # file loads: Minitest::Assertion when Minitest is already loaded, so that a
10
+ # failed assertion is reported as a failure and not as an error in a Minitest
11
+ # run; StandardError otherwise, so that this file loads alone. Require
12
+ # "minitest/autorun" before "ruby_cdk/test". Under Minitest the class descends
13
+ # from Exception, so a bare `rescue` does not catch it, as for any other
14
+ # Minitest assertion failure. The class is built with Class.new because its
15
+ # parent is not known until load time. The symbol that marks the class there is
16
+ # not reproduced: `is_a?(RubyCdk::Test::AssertionError)` answers the same question.
17
+
18
+ module RubyCdk
19
+ module Test
20
+ MINITEST_ASSERTION = if Object.const_defined?("Minitest", false) &&
21
+ Object.const_get("Minitest", false).const_defined?(:Assertion, false)
22
+ Object.const_get("Minitest", false).const_get(:Assertion, false)
23
+ end
24
+ private_constant :MINITEST_ASSERTION
25
+
26
+ # Thrown from the assertions module when an assertion fails. Assertion errors
27
+ # are directly connected to an assertion a user wrote.
28
+ #
29
+ # Not every error of the module is an AssertionError. The CDK says a wrong
30
+ # precondition (a matcher used where it cannot be) is better reported another
31
+ # way, but raises this class for it; so does this port, for that and for a
32
+ # template with a dependency cycle. Where JavaScript itself throws a TypeError
33
+ # (a null where an object was needed), so does this port.
34
+ AssertionError = Class.new(MINITEST_ASSERTION || StandardError) do
35
+ # The time the error was thrown, as an ISO 8601 timestamp.
36
+ attr_reader :time
37
+
38
+ def type
39
+ "assertion"
40
+ end
41
+
42
+ def initialize(msg = nil)
43
+ super(msg)
44
+ @time = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ")
45
+ end
46
+ end
47
+ end
48
+ end