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,291 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require_relative "construct"
5
+ require_relative "elements"
6
+ require_relative "stateful"
7
+
8
+ module RubyCdk
9
+ # One template. Built from a block evaluated in its own context, or from a
10
+ # subclass that overrides build.
11
+ class Stack < Construct
12
+ # CloudFormation's rule for a stack name: a letter, then letters, digits and hyphens.
13
+ NAME_PATTERN = /\A[A-Za-z][A-Za-z0-9-]*\z/
14
+ MAX_NAME_LENGTH = 128
15
+
16
+ # unique_name ends with this many hex characters of a SHA-256.
17
+ UNIQUE_NAME_HASH_LENGTH = 8
18
+
19
+ # The longest description a stack can carry: CloudFormation's limit, which
20
+ # the CDK refuses too (StackDescriptionTooLong).
21
+ MAX_DESCRIPTION_LENGTH = 512
22
+
23
+ # Shorter than this, no name is a valid S3 bucket name.
24
+ MIN_UNIQUE_NAME_LENGTH = 3
25
+
26
+ # The longest S3 bucket name: a unique_name with the default is always one.
27
+ DEFAULT_UNIQUE_NAME_MAX_LENGTH = 63
28
+
29
+ attr_reader :stack_name, :termination_protection, :app, :env, :description, :tags, :stateful_default
30
+
31
+ def initialize(scope, id, env: nil, description: nil, tags: {}, stateful_default: nil, termination_protection: false, &block)
32
+ unless scope.is_a?(App)
33
+ raise UsageError, "A Stack is created in an App: Stack.new(app, #{id.inspect}), got #{scope.inspect} as its scope"
34
+ end
35
+ if env && !env.is_a?(Env)
36
+ raise UsageError, "Stack #{id.inspect}: env must be a RubyCdk::Env, got #{env.inspect}"
37
+ end
38
+
39
+ super(scope, id)
40
+ @app = scope
41
+ @stack_name = "#{scope.stack_name_prefix}#{self.id}"
42
+ @env = env || scope.env
43
+ @description = description && described(description)
44
+ @tags = tag_hash(tags)
45
+ @stateful_default = Core::Stateful.validate_default!(stateful_default || scope.stateful_default)
46
+ @termination_protection = termination_protection ? true : false
47
+
48
+ @resources = []
49
+ @parameters = {}
50
+ @outputs = {}
51
+ @mappings = {}
52
+ @conditions = {}
53
+ @metadata = {}
54
+ @dependencies = []
55
+ @transforms = []
56
+
57
+ if block
58
+ instance_eval(&block)
59
+ else
60
+ build
61
+ end
62
+ end
63
+
64
+ # What a subclass defines instead of passing a block.
65
+ def build
66
+ end
67
+
68
+ def parameter(id, type:, default: nil, description: nil, allowed_values: nil, no_echo: false)
69
+ declare(@parameters, id, "parameter") do |name|
70
+ Core::Parameter.new(self, name, type:, default:, description:, allowed_values:, no_echo:)
71
+ end
72
+ end
73
+
74
+ def output(id, value:, description: nil, export: false, condition: nil)
75
+ name_of_condition = Core::Ids.condition_name(condition, "#{path}: output #{id.inspect}")
76
+ declare(@outputs, id, "output") do |name|
77
+ Core::Output.new(self, name, value:, description:, export:, condition: name_of_condition)
78
+ end
79
+ end
80
+
81
+ # An output whose Export name is export_name(id).
82
+ def export(id, value:, description: nil)
83
+ output(id, value:, description:, export: true)
84
+ end
85
+
86
+ # "#{stack_name}-#{id}", the name under which `export(id, ...)` exports. id
87
+ # is the id of an output, so it follows the same rule as one.
88
+ def export_name(id)
89
+ name = Core::Ids.validate_id!(id, scope: self)
90
+ Core::Ids.validate_logical_id!(name, where: "#{path}: the output #{name.inspect} that export_name names")
91
+
92
+ "#{stack_name}-#{name}"
93
+ end
94
+
95
+ def mapping(id, hash)
96
+ declare(@mappings, id, "mapping") { |name| Core::Mapping.new(self, name, hash) }
97
+ end
98
+
99
+ def condition(id, fn)
100
+ declare(@conditions, id, "condition") { |name| Core::Condition.new(self, name, fn) }
101
+ end
102
+
103
+ # Adds to the template's Metadata section.
104
+ def add_metadata(key, value)
105
+ @metadata[text(key, "metadata key")] = value
106
+ self
107
+ end
108
+
109
+ # Declares a transform for the template, written as its Transform section:
110
+ # a macro that Fn.transform calls, or AWS::Serverless-2016-10-31. Declaring
111
+ # one twice changes nothing.
112
+ #
113
+ # Synthesis calls it too: a value that CloudFormation accepts only under a
114
+ # transform gets that transform, as a stack in the CDK does.
115
+ def transform(name)
116
+ name = text(name, "transform")
117
+ @transforms << name unless @transforms.include?(name)
118
+ self
119
+ end
120
+
121
+ # Every transform the template declares, in the order they were declared.
122
+ def transforms
123
+ @transforms.dup.freeze
124
+ end
125
+
126
+ # The builder of the stack's file assets.
127
+ #
128
+ # Declared here because it is the tree's contract. The assets component
129
+ # implements it by reopening this class: core does not depend on assets.
130
+ def asset
131
+ raise NotImplementedError, "added by the assets component"
132
+ end
133
+
134
+ # "#{stack_name}-#{suffix}-<hash>": lower-case letters, digits and hyphens.
135
+ # The hash is the first eight hex characters of SHA-256 over
136
+ # "account:region:stack_name:suffix", so the name is stable across deploys
137
+ # and different in another account or region. A name longer than
138
+ # max_length is shortened from the left. Needs a concrete env.
139
+ #
140
+ # With the default max_length the name is always a valid S3 bucket name:
141
+ # 3 to 63 characters, starting and ending with a letter or a digit. A
142
+ # service whose names may be longer takes a larger max_length.
143
+ def unique_name(suffix = nil, max_length: DEFAULT_UNIQUE_NAME_MAX_LENGTH)
144
+ unless env
145
+ raise UsageError, "#{path}: unique_name needs a concrete env. Give the Stack or its App " \
146
+ "env: RubyCdk::Env.new(account:, region:)"
147
+ end
148
+ unless max_length.is_a?(Integer) && max_length >= MIN_UNIQUE_NAME_LENGTH
149
+ raise UsageError, "#{path}: unique_name takes max_length: of at least #{MIN_UNIQUE_NAME_LENGTH}, got #{max_length.inspect}"
150
+ end
151
+
152
+ digest = Digest::SHA256.hexdigest("#{env.account}:#{env.region}:#{stack_name}:#{suffix}")[0, UNIQUE_NAME_HASH_LENGTH]
153
+ name = [ stack_name, suffix&.to_s ].compact.map { |part| name_word(part) }.reject(&:empty?).join("-")
154
+ name = "#{name.empty? ? "" : "#{name}-"}#{digest}"
155
+ # Shortened from the left: its last max_length characters.
156
+ name = name[name.length - max_length, max_length] || name if name.length > max_length
157
+ name.delete_prefix("-")
158
+ end
159
+
160
+ # Makes this stack deploy after another one.
161
+ #
162
+ # A cycle is refused here and now, as the CDK refuses one at
163
+ # addStackDependency ("cyclic reference", core/lib/stack.ts:1044): walking
164
+ # the other stack's dependencies finds this stack before the deploy order
165
+ # would.
166
+ def add_dependency(other)
167
+ unless other.is_a?(Stack)
168
+ raise UsageError, "#{path}: add_dependency takes a Stack, got #{other.inspect}"
169
+ end
170
+ raise UsageError, "#{path}: a stack cannot depend on itself" if other.equal?(self)
171
+
172
+ reached = reaches?(other, self)
173
+ if reached
174
+ raise UsageError, "#{path}: depending on #{other.stack_name} makes a cyclic reference: " \
175
+ "#{other.stack_name} already depends on #{stack_name}, directly or through the stacks between them"
176
+ end
177
+
178
+ @dependencies << other unless @dependencies.include?(other)
179
+ self
180
+ end
181
+
182
+ # Runs every phase of architecture §5 except write and returns the template as a Hash.
183
+ #
184
+ # Declared here because it is the tree's contract. The synth component
185
+ # implements it by reopening this class: core does not depend on synth.
186
+ def to_template
187
+ raise NotImplementedError, "added by the synth component"
188
+ end
189
+
190
+ # The stacks this one depends on, in the order they were added.
191
+ def dependencies
192
+ @dependencies.dup.freeze
193
+ end
194
+
195
+ # What the stack declares, in declaration order. Synthesis reads them.
196
+ def resources
197
+ @resources.dup.freeze
198
+ end
199
+
200
+ def parameters
201
+ @parameters.dup.freeze
202
+ end
203
+
204
+ def outputs
205
+ @outputs.dup.freeze
206
+ end
207
+
208
+ def mappings
209
+ @mappings.dup.freeze
210
+ end
211
+
212
+ def conditions
213
+ @conditions.dup.freeze
214
+ end
215
+
216
+ def metadata
217
+ @metadata.dup.freeze
218
+ end
219
+
220
+ # Adds a resource to this stack's Resources, in creation order. The cfn
221
+ # component calls it when a resource is created in the tree.
222
+ def register_resource(resource)
223
+ @resources << resource
224
+ resource
225
+ end
226
+
227
+ private
228
+
229
+ # The stack's description: a String or a Symbol, at most MAX_DESCRIPTION_LENGTH
230
+ # characters, as the CDK refuses a longer one (StackDescriptionTooLong,
231
+ # core/lib/stack.ts).
232
+ def described(description)
233
+ text = text(description, "description")
234
+ if text.length > MAX_DESCRIPTION_LENGTH
235
+ raise UsageError, "#{path}: the description is #{text.length} characters, and at most " \
236
+ "#{MAX_DESCRIPTION_LENGTH} are taken (CloudFormation's limit, the CDK's StackDescriptionTooLong)"
237
+ end
238
+
239
+ text
240
+ end
241
+
242
+ # Whether walking target's dependencies, through the stacks between them,
243
+ # reaches the wanted stack.
244
+ def reaches?(target, wanted)
245
+ seen = [ self ]
246
+ frontier = [ target ]
247
+ until frontier.empty?
248
+ current = frontier.pop
249
+ return true if current.equal?(wanted)
250
+ next if seen.include?(current)
251
+
252
+ seen << current
253
+ frontier.concat(current.dependencies)
254
+ end
255
+ false
256
+ end
257
+
258
+ # Declares an element under its id. The id has to be a logical ID that
259
+ # CloudFormation takes, here and now: kind names it in the message.
260
+ def declare(collection, id, kind)
261
+ name = Core::Ids.validate_id!(id, scope: self)
262
+ Core::Ids.validate_logical_id!(name, where: "#{path}: the #{kind} #{name.inspect}")
263
+ if collection.key?(name)
264
+ raise UsageError, "#{path} declares #{name.inspect} twice"
265
+ end
266
+
267
+ collection[name] = yield name
268
+ end
269
+
270
+ # A String or a Symbol, as a String.
271
+ def text(value, what)
272
+ return value if value.is_a?(String)
273
+ return value.name if value.is_a?(Symbol)
274
+
275
+ raise UsageError, "#{path}: #{what} must be a String or a Symbol, got #{value.inspect}"
276
+ end
277
+
278
+ def tag_hash(tags)
279
+ unless tags.is_a?(Hash)
280
+ raise UsageError, "#{path}: tags takes a Hash, got #{tags.inspect}"
281
+ end
282
+
283
+ tags.to_h { |key, value| [ text(key, "tag key"), text(value, "tag value") ] }.freeze
284
+ end
285
+
286
+ # Lower-case letters and digits; every run of anything else becomes one hyphen.
287
+ def name_word(part)
288
+ part.downcase.gsub(/[^a-z0-9]+/, "-").delete_prefix("-").delete_suffix("-")
289
+ end
290
+ end
291
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+
5
+ module RubyCdk
6
+ module Core
7
+ # The safe defaults of architecture §7 (D-007): the resource types the CDK
8
+ # retains are retained here from the first deploy, per resource type and
9
+ # with no schema needed.
10
+ #
11
+ # The list was read in the CDK's source on 2026-11-23, at commit
12
+ # 78649cb7cf7399204ed63f629964779eeaa8b37a, and completed on 2026-11-25 at
13
+ # commit 68b2516c09791d78b199f30e455e4670dc9cde6d: each of these L2
14
+ # constructs ends with `applyRemovalPolicy(props.removalPolicy)`, which
15
+ # defaults to `RemovalPolicy.RETAIN` (cfn-resource.ts:143), and the ones
16
+ # given `{ default: RemovalPolicy.RETAIN }` or RETAIN outright
17
+ # (AppConfig's HostedConfigurationVersion) are retained all the same; the
18
+ # RDS ones pass `?? RemovalPolicy.SNAPSHOT`.
19
+ #
20
+ # One value sets both attributes, as the CDK's removal policy does
21
+ # (cfn-resource.ts, applyRemovalPolicy): Delete is Delete and Delete,
22
+ # Retain is Retain and Retain, RetainExceptOnCreate is RetainExceptOnCreate
23
+ # and Retain, Snapshot is Snapshot and Snapshot.
24
+ module Stateful
25
+ # The two values of `stateful_default:`.
26
+ DEFAULTS = %i[retain_except_on_create delete].freeze
27
+
28
+ # Retained by the CDK, and here. AWS::ApiGateway::Deployment stays out:
29
+ # the CDK retains it only when the app opts in with retainDeployments,
30
+ # whose default is false (aws-apigateway/lib/deployment.ts:35,108-109).
31
+ RETAINED_TYPES = %w[
32
+ AWS::S3::Bucket
33
+ AWS::DynamoDB::Table
34
+ AWS::Logs::LogGroup
35
+ AWS::Logs::LogStream
36
+ AWS::KMS::Key
37
+ AWS::EC2::Volume
38
+ AWS::ECR::Repository
39
+ AWS::Cognito::UserPool
40
+ AWS::Kinesis::Stream
41
+ AWS::OpenSearchService::Domain
42
+ AWS::Elasticsearch::Domain
43
+ AWS::Glue::Database
44
+ AWS::Backup::BackupVault
45
+ AWS::CodeBuild::ReportGroup
46
+ AWS::Scheduler::ScheduleGroup
47
+ AWS::DocDB::DBCluster
48
+ AWS::DocDB::DBInstance
49
+ AWS::FSx::FileSystem
50
+ AWS::AppConfig::HostedConfigurationVersion
51
+ ].freeze
52
+
53
+ # Snapshotted by the CDK, and here.
54
+ SNAPSHOT_TYPES = %w[
55
+ AWS::RDS::DBInstance
56
+ AWS::RDS::DBCluster
57
+ ].freeze
58
+
59
+ DELETION_POLICIES = {
60
+ delete: "Delete",
61
+ retain: "Retain",
62
+ retain_except_on_create: "RetainExceptOnCreate",
63
+ snapshot: "Snapshot"
64
+ }.freeze
65
+
66
+ # CloudFormation accepts no RetainExceptOnCreate for UpdateReplacePolicy (rule V16).
67
+ UPDATE_REPLACE_POLICIES = {
68
+ delete: "Delete",
69
+ retain: "Retain",
70
+ snapshot: "Snapshot"
71
+ }.freeze
72
+
73
+ # What a deletion policy means for [DeletionPolicy, UpdateReplacePolicy].
74
+ PAIRS = {
75
+ "Delete" => %w[ Delete Delete ],
76
+ "Retain" => %w[ Retain Retain ],
77
+ "RetainExceptOnCreate" => %w[ RetainExceptOnCreate Retain ],
78
+ "Snapshot" => %w[ Snapshot Snapshot ]
79
+ }.freeze
80
+
81
+ module_function
82
+
83
+ # [DeletionPolicy, UpdateReplacePolicy] for a resource type when the user
84
+ # gave neither, or nil for a type that is not stateful.
85
+ #
86
+ # Under `:delete` both are written out rather than left out, as they are
87
+ # when a CDK construct is told RemovalPolicy.DESTROY: CloudFormation's own
88
+ # default for an RDS instance is a snapshot, and the user asked for a
89
+ # teardown that leaves nothing behind.
90
+ def policies_for(type, default:)
91
+ kind = stateful_kind(type)
92
+ return nil unless kind
93
+
94
+ if default == :delete
95
+ PAIRS.fetch("Delete")
96
+ else
97
+ PAIRS.fetch(kind == :snapshot ? "Snapshot" : "RetainExceptOnCreate")
98
+ end
99
+ end
100
+
101
+ def stateful?(type)
102
+ !stateful_kind(type).nil?
103
+ end
104
+
105
+ # [DeletionPolicy, UpdateReplacePolicy] for a deletion policy the user gave.
106
+ def pair(deletion_policy)
107
+ PAIRS.fetch(deletion_policy)
108
+ end
109
+
110
+ # Raises UsageError unless value is one of the two defaults. Returns it as a Symbol.
111
+ def validate_default!(value)
112
+ choice = DEFAULTS.find { |candidate| candidate.to_s == value.to_s }
113
+ unless choice
114
+ Kernel.raise UsageError, "stateful_default: #{value.inspect} is not one of #{DEFAULTS.map(&:inspect).join(", ")}"
115
+ end
116
+
117
+ choice
118
+ end
119
+
120
+ # The CloudFormation name of a `deletion_policy:` as the user wrote it
121
+ # (a Symbol or the name itself), nil when absent. Anything else is a
122
+ # UsageError, whose message starts with where when it is given.
123
+ def deletion_policy(value, where: nil)
124
+ policy(value, DELETION_POLICIES, "deletion_policy", where)
125
+ end
126
+
127
+ # The same for `update_replace_policy:`.
128
+ def update_replace_policy(value, where: nil)
129
+ policy(value, UPDATE_REPLACE_POLICIES, "update_replace_policy", where)
130
+ end
131
+
132
+ # :retained or :snapshot for a stateful type, nil for any other.
133
+ def stateful_kind(type)
134
+ if RETAINED_TYPES.include?(type)
135
+ :retained
136
+ elsif SNAPSHOT_TYPES.include?(type)
137
+ :snapshot
138
+ end
139
+ end
140
+
141
+ def policy(value, names, keyword, where)
142
+ return nil if value.nil?
143
+
144
+ canonical = names[value] || (names.value?(value) ? value : nil)
145
+ unless canonical
146
+ allowed = names.values.join(", ")
147
+ prefix = where ? "#{where}: " : ""
148
+ Kernel.raise UsageError, "#{prefix}#{keyword}: #{value.inspect} is not one of #{allowed}"
149
+ end
150
+
151
+ canonical
152
+ end
153
+ private_class_method :stateful_kind, :policy
154
+ end
155
+ end
156
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "values"
4
+ require_relative "core/ids"
5
+ require_relative "core/stateful"
6
+ require_relative "core/elements"
7
+ require_relative "core/construct"
8
+ require_relative "core/stack"
9
+ require_relative "core/app"
10
+
11
+ module RubyCdk
12
+ # The tree: an App of Stacks of Constructs.
13
+ module Core
14
+ end
15
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Deploy
5
+ # The capabilities a template needs, read from its resources and never from
6
+ # a flag. CloudFormation refuses a change set that lacks one it needs.
7
+ module Capabilities
8
+ IAM = "CAPABILITY_IAM"
9
+ NAMED_IAM = "CAPABILITY_NAMED_IAM"
10
+
11
+ # The eight resource types CloudFormation lists as needing a capability.
12
+ IAM_TYPES = %w[
13
+ AWS::IAM::AccessKey
14
+ AWS::IAM::Group
15
+ AWS::IAM::InstanceProfile
16
+ AWS::IAM::ManagedPolicy
17
+ AWS::IAM::Policy
18
+ AWS::IAM::Role
19
+ AWS::IAM::User
20
+ AWS::IAM::UserToGroupAddition
21
+ ].freeze
22
+
23
+ # The properties that give an IAM resource an explicit name. A name counts
24
+ # wherever one of them is set on one of the eight types: saying
25
+ # CAPABILITY_NAMED_IAM too often is harmless, and saying it too seldom
26
+ # makes CloudFormation refuse the change set.
27
+ NAME_PROPERTIES = %w[RoleName ManagedPolicyName UserName GroupName InstanceProfileName].freeze
28
+
29
+ # template is a parsed template. The answer is empty when none is needed;
30
+ # otherwise CAPABILITY_IAM, and CAPABILITY_NAMED_IAM with it when a name is set.
31
+ def self.for(template)
32
+ resources = template["Resources"]
33
+ iam = (resources.is_a?(Hash) ? resources.values.grep(Hash) : []).select { |resource| IAM_TYPES.include?(resource["Type"]) }
34
+ return [] if iam.empty?
35
+
36
+ named = iam.any? do |resource|
37
+ properties = resource["Properties"]
38
+ properties.is_a?(Hash) && NAME_PROPERTIES.any? { |property| !properties[property].nil? }
39
+ end
40
+ named ? [ IAM, NAMED_IAM ] : [ IAM ]
41
+ end
42
+ end
43
+ end
44
+ end