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,289 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "version"
4
+ require_relative "errors"
5
+ require_relative "core"
6
+ require_relative "cfn"
7
+ require_relative "synth"
8
+ require_relative "deploy"
9
+
10
+ module RubyCdk
11
+ # The asset bucket as a stack of this tool's own (architecture §8): a stack
12
+ # named `ruby-cdk-bootstrap` holding one bucket, `ruby-cdk-assets-<account>-<region>`,
13
+ # versioned, encrypted with SSE-S3, with public access blocked and multipart
14
+ # uploads aborted, retained when the stack is deleted, and its policy denying
15
+ # everything that does not come over TLS. A command builds it with `stack`,
16
+ # checks the ground with `pre_flight`, and deploys it with `run` through the
17
+ # deploy engine.
18
+ #
19
+ # This file is the entry of the `bootstrap` component. It loads the pipeline
20
+ # (which brings the tree, the L1 resources and the serializer) and the engine
21
+ # (which brings the ports). It never loads the AWS SDK: the command that calls
22
+ # `run` builds `clients` with `Deploy::Sdk`, which the adapters component owns.
23
+ module Bootstrap
24
+ # The name of the bootstrap stack, as architecture §8 fixes it.
25
+ STACK_NAME = "ruby-cdk-bootstrap"
26
+
27
+ # The logical IDs of the two resources. The bucket's logical ID is named in
28
+ # the orphan-bucket refusal, because the import way out has to use it.
29
+ BUCKET_ID = "AssetsBucket"
30
+ POLICY_ID = "BucketPolicy"
31
+
32
+ # The stack tag: what integration sweepers and humans recognise it by.
33
+ TAG_NAME = "ruby-cdk"
34
+
35
+ # The asset bucket's name: a function of public facts, exactly what
36
+ # Assets.bucket_name answers. It is computed here, and not read from the
37
+ # assets component, because the component map keeps the two apart (an asset
38
+ # is declared by a user's stack, the bucket is this tool's own). A test pins
39
+ # the two to the same bytes, so they cannot drift.
40
+ BUCKET_PREFIX = "ruby-cdk-assets-"
41
+
42
+ # Exit 1. The asset bucket exists and is owned by the caller's account, but
43
+ # no bootstrap stack does, so bootstrap cannot adopt it as it is: the two
44
+ # ways out are in the message.
45
+ class OrphanBucket < PreconditionError; end
46
+
47
+ # Exit 1. The asset bucket exists and is owned by another account. Nothing
48
+ # is created.
49
+ class ForeignBucket < PreconditionError; end
50
+
51
+ # What pre_flight decided, for the command to show before it deploys.
52
+ #
53
+ # action :create (a first deploy), :update (the stack is stable) or
54
+ # :deploy (the engine decides; it refuses a busy stack or one
55
+ # that needs repair, and deletes and recreates a failed creation)
56
+ # stack_state the engine's own state of the stack, one of Deploy::STACK_STATES
57
+ # bucket the bucket's name
58
+ # bucket_state :mine, :foreign or :absent
59
+ Decision = Data.define(:action, :stack_state, :bucket, :bucket_state)
60
+
61
+ class << self
62
+ # Builds the bootstrap stack in the App it is given, and returns it. The
63
+ # command synthesizes and deploys it (run does both); a test synthesizes
64
+ # it alone.
65
+ #
66
+ # The App needs a concrete env, because the bucket's name is made of the
67
+ # account and the region. The stack carries the `ruby-cdk` tag with the
68
+ # gem version, so that sweepers and humans recognise it.
69
+ #
70
+ # deployer_arn: the ARN of the principal that reads the assets back out of
71
+ # the bucket, given as `--deployer` by the command. Nothing, or nil: the
72
+ # policy grants the account's own principals (`arn:aws:iam::<account>:root`,
73
+ # the default the CDK's bootstrap template trusts too). The engine refuses
74
+ # to deploy the stack into an account other than its env's, so the root
75
+ # grant always covers the caller, and it cannot go stale the way a session
76
+ # ARN would.
77
+ def stack(app:, deployer_arn: nil)
78
+ unless app.is_a?(App)
79
+ raise UsageError, "Bootstrap.stack builds the bootstrap stack in an App, got #{app.inspect}. " \
80
+ "Create the App with env: RubyCdk::Env.new(account:, region:) and pass it."
81
+ end
82
+ env = app.env
83
+ raise UsageError, MISSING_ENV unless env
84
+
85
+ bucket = bucket_name(env.account, env.region)
86
+ stack = Stack.new(app, STACK_NAME, tags: { TAG_NAME => RubyCdk::VERSION })
87
+
88
+ assets = stack.resource(BUCKET_ID, "AWS::S3::Bucket",
89
+ BucketName: bucket,
90
+ BucketEncryption: { "ServerSideEncryptionConfiguration" =>
91
+ [ { "ServerSideEncryptionByDefault" => { "SSEAlgorithm" => "AES256" } } ] },
92
+ PublicAccessBlockConfiguration: PUBLIC_ACCESS_BLOCK.dup,
93
+ VersioningConfiguration: { "Status" => "Enabled" },
94
+ LifecycleConfiguration: { "Rules" => [ MULTIPART_RULE.dup ] },
95
+ deletion_policy: :retain,
96
+ update_replace_policy: :retain)
97
+
98
+ stack.resource(POLICY_ID, "AWS::S3::BucketPolicy",
99
+ Bucket: Fn.ref(assets),
100
+ PolicyDocument: policy_document(bucket, principal_of(deployer_arn, env.account)))
101
+
102
+ stack
103
+ end
104
+
105
+ # What has to be true before anything is created, answered as a Decision.
106
+ # The bucket is checked first (one call of the object-store port, with the
107
+ # identity's account as the expected owner), because a bucket that is not
108
+ # ours stops everything; then the stack's state is read through the
109
+ # engine's own machinery, the port that both the adapter and the engine
110
+ # classify with. Nothing here creates anything; the states the engine
111
+ # refuses it refuses itself, with its own words.
112
+ #
113
+ # stack of the account bucket :absent → :create
114
+ # stack of the account bucket ours → refused: OrphanBucket
115
+ # stack of the account bucket foreign → refused: ForeignBucket
116
+ # stack :review bucket :absent → :create (the engine creates again)
117
+ # stack :review bucket ours → refused: OrphanBucket
118
+ # stack :stable bucket ours → :update (the engine's idempotency skips
119
+ # it when nothing changed)
120
+ # stack :stable bucket :absent → :update; the Decision says so, and run
121
+ # announces that this deploy does not
122
+ # recreate the bucket
123
+ # stack :stable bucket foreign → refused: ForeignBucket
124
+ # stack :rollback_complete bucket :absent → :create (the engine deletes the failed
125
+ # stack and creates again)
126
+ # stack :rollback_complete bucket ours → refused: OrphanBucket
127
+ # stack :busy any → :deploy (the engine refuses: StackBusy)
128
+ # stack :rollback_failed any → :deploy (the engine refuses: StackNeedsRepair)
129
+ #
130
+ # A stack in :review or :rollback_complete owns nothing: a change set that
131
+ # was never executed, or a first creation that failed, has made no bucket.
132
+ # That is why the bucket rows of those states are the same as :absent.
133
+ def pre_flight(client:, store:, identity:, env:, stack_name: STACK_NAME)
134
+ bucket = bucket_name(env.account, env.region)
135
+ bucket_state = store.bucket_state(bucket, expected_owner: identity.account)
136
+ raise ForeignBucket, foreign_message(bucket, identity.account, env.account) if bucket_state == :foreign
137
+
138
+ state = client.stack_state(stack_name)
139
+ action =
140
+ case state
141
+ when :absent, :review, :rollback_complete
142
+ raise OrphanBucket, orphan_message(bucket, stack_name, identity.account) if bucket_state == :mine
143
+
144
+ :create
145
+ when :stable
146
+ :update
147
+ else
148
+ # :busy and :rollback_failed. The engine refuses both on its own, with
149
+ # its own words: StackBusy, or StackNeedsRepair with the repair path.
150
+ :deploy
151
+ end
152
+
153
+ Decision.new(action: action, stack_state: state, bucket: bucket, bucket_state: bucket_state)
154
+ end
155
+
156
+ # The whole of `ruby-cdk bootstrap`, for the command: builds the stack in
157
+ # the App it is given, asks the client who the credentials are for, runs
158
+ # the pre-flight, synthesizes (locally, before any request), and deploys
159
+ # through the engine. Answers the engine's DeployResult, whose exit_code
160
+ # is the command's.
161
+ #
162
+ # clients is the pair the adapters build (Sdk.clients: cfn and store).
163
+ # options is a Deploy::DeployOptions; yes comes from the command, which
164
+ # owns --yes. Nothing is published: the bootstrap stack has no assets,
165
+ # and a stack with no assets uploads nothing.
166
+ def run(app:, clients:, output:, deployer_arn: nil, options: nil)
167
+ stack = Bootstrap.stack(app:, deployer_arn:)
168
+ identity = clients.cfn.resolve_identity
169
+ decision = pre_flight(client: clients.cfn, store: clients.store, identity:, env: stack.env,
170
+ stack_name: stack.stack_name)
171
+ output.announce(missing_bucket_note(decision, stack.stack_name)) if missing_bucket?(decision)
172
+
173
+ synthesized = Synth.synthesize(stack)
174
+ Deploy::Deployer.new(client: clients.cfn, store: clients.store, output:).deploy(
175
+ stack: stack, template: synthesized.bytes, identity: identity, options: options || Deploy::DeployOptions.new
176
+ )
177
+ end
178
+
179
+ # The asset bucket of an account in a region: the same bytes
180
+ # Assets.bucket_name answers (see BUCKET_PREFIX above).
181
+ def bucket_name(account, region)
182
+ "#{BUCKET_PREFIX}#{account}-#{region}"
183
+ end
184
+
185
+ private
186
+
187
+ # Public access blocked on all four settings, as architecture §8 asks.
188
+ # The resource takes its own copy: properties belong to the resource.
189
+ PUBLIC_ACCESS_BLOCK = {
190
+ "BlockPublicAcls" => true,
191
+ "BlockPublicPolicy" => true,
192
+ "IgnorePublicAcls" => true,
193
+ "RestrictPublicBuckets" => true
194
+ }.freeze
195
+
196
+ # Incomplete multipart uploads are aborted a day after they start: an
197
+ # asset zip finishes in minutes, so anything older is a leftover that
198
+ # would otherwise be billed forever.
199
+ MULTIPART_RULE = {
200
+ "Id" => "abort-incomplete-multipart-uploads",
201
+ "Status" => "Enabled",
202
+ "AbortIncompleteMultipartUpload" => { "DaysAfterInitiation" => 1 }
203
+ }.freeze
204
+
205
+ MISSING_ENV = "Bootstrap needs a concrete env, because the asset bucket's name is made of the account and " \
206
+ "the region (ruby-cdk-assets-<account>-<region>). Create the App with env: RubyCdk::Env.new(account:, region:)."
207
+
208
+ def principal_of(deployer_arn, account)
209
+ return "arn:aws:iam::#{account}:root" if deployer_arn.nil?
210
+
211
+ arn = deployer_arn.to_s
212
+ if arn.strip.empty?
213
+ raise UsageError, "Bootstrap: deployer_arn was given blank (#{deployer_arn.inspect}). Give the ARN of the " \
214
+ "principal that reads the assets (--deployer arn:aws:iam::<account>:role/deployer), or nothing, to grant " \
215
+ "the account's own principals."
216
+ end
217
+
218
+ arn
219
+ end
220
+
221
+ # The two statements of the bucket's policy: deny everything that does not
222
+ # come over TLS, on the bucket and on its objects; and let the deployer
223
+ # read the objects back, because CloudFormation reads a TemplateURL with
224
+ # the caller's permissions, so the grant has to name it (architecture §8).
225
+ # Asset keys sit at the root as <hash>.zip, so the read is on every object.
226
+ def policy_document(bucket, principal)
227
+ {
228
+ "Version" => "2012-10-17",
229
+ "Statement" => [
230
+ {
231
+ "Sid" => "DenyInsecureTransport",
232
+ "Effect" => "Deny",
233
+ "Principal" => "*",
234
+ "Action" => "s3:*",
235
+ "Resource" => [ "arn:aws:s3:::#{bucket}", "arn:aws:s3:::#{bucket}/*" ],
236
+ "Condition" => { "Bool" => { "aws:SecureTransport" => "false" } }
237
+ },
238
+ {
239
+ "Sid" => "DeployerReadsAssets",
240
+ "Effect" => "Allow",
241
+ "Principal" => { "AWS" => principal },
242
+ "Action" => "s3:GetObject",
243
+ "Resource" => "arn:aws:s3:::#{bucket}/*"
244
+ }
245
+ ]
246
+ }
247
+ end
248
+
249
+ # The bucket exists and is ours, but no bootstrap stack does: bootstrap
250
+ # cannot go on, and there are two ways out (architecture §8).
251
+ def orphan_message(bucket, stack_name, account)
252
+ "The asset bucket #{bucket} exists in account #{account}, but the bootstrap stack #{stack_name} does not, " \
253
+ "so bootstrap stops: creating the stack would try to make a bucket that already has that name. " \
254
+ "Nothing was created or changed.\n" \
255
+ "Two ways out:\n" \
256
+ " - the bucket is empty: empty it and delete it in the S3 console, then run `ruby-cdk bootstrap` again;\n" \
257
+ " - the bucket holds objects to keep: import the bucket into stack #{stack_name} with CloudFormation " \
258
+ "resource import (a change set of type IMPORT, logical ID #{BUCKET_ID}), then run `ruby-cdk bootstrap` again."
259
+ end
260
+
261
+ # The bucket exists and is not ours: bootstrap stops before anything is
262
+ # created (architecture §8, D-008: the name is a function of public facts).
263
+ def foreign_message(bucket, identity_account, env_account)
264
+ "The asset bucket #{bucket} exists, but it is not owned by account #{identity_account}, which is who the " \
265
+ "credentials are for (S3 answers 403 Forbidden when a bucket belongs to another account), so bootstrap " \
266
+ "stops before anything is created. Bucket names are global: whoever holds the name would receive what " \
267
+ "this tool uploads to it.\n" \
268
+ "Run the command again with credentials of account #{env_account}, the one the stack's env names " \
269
+ "(--profile NAME), or give the App an env for the account these credentials are for."
270
+ end
271
+
272
+ # The stack is there and the bucket is not. Deploying does not mend it:
273
+ # the bucket's name is part of the deployed template, so CloudFormation
274
+ # sees no change and makes no bucket. The first deploy of a stack with
275
+ # assets then refuses ("Run `ruby-cdk bootstrap` first"), which is the
276
+ # honest outcome, but it should not be a surprise.
277
+ def missing_bucket?(decision)
278
+ decision.action == :update && decision.bucket_state == :absent
279
+ end
280
+
281
+ def missing_bucket_note(decision, stack_name)
282
+ "The asset bucket #{decision.bucket} does not exist, although the bootstrap stack #{stack_name} does. " \
283
+ "This deploy does not recreate a bucket the template already names, and the first deploy of a stack " \
284
+ "with assets will refuse until the bucket is there. If the bucket was deleted by hand, destroy the " \
285
+ "bootstrap stack (`ruby-cdk destroy #{stack_name}`), then run `ruby-cdk bootstrap` again."
286
+ end
287
+ end
288
+ end
289
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../core/ids"
5
+ require_relative "../core/stateful"
6
+ require_relative "../core/construct"
7
+
8
+ module RubyCdk
9
+ # The tree's contract declares Construct#resource. This is its
10
+ # implementation, in the component that knows what a resource is.
11
+ class Construct
12
+ # Registers an L1 resource in the nearest Stack and returns it.
13
+ #
14
+ # opts are the properties, or properties: holds them under their exact
15
+ # CloudFormation names; the two cannot be combined.
16
+ def resource(id, type, properties: nil, depends_on: [], condition: nil, deletion_policy: nil, update_replace_policy: nil, metadata: {}, **opts)
17
+ if properties && !opts.empty?
18
+ raise UsageError, "resource #{id.inspect} in #{path}: #{Cfn::Resource::BOTH_PROPERTIES}"
19
+ end
20
+
21
+ Cfn::Resource.new(self, id, type:, properties: properties || opts, depends_on:, condition:, deletion_policy:, update_replace_policy:, metadata:)
22
+ end
23
+ end
24
+
25
+ module Cfn
26
+ # L1: a direct mapping to a CloudFormation resource.
27
+ #
28
+ # Its logical ID is its id when it sits directly in a Stack, and the ids of
29
+ # the constructs around it joined in front of its own otherwise.
30
+ class Resource < Construct
31
+ BOTH_PROPERTIES = "properties: cannot be combined with other keywords. Pass every property as a keyword, or all of them inside properties: { ... }"
32
+
33
+ attr_reader :type, :logical_id, :properties, :depends_on, :condition, :deletion_policy, :update_replace_policy, :metadata
34
+
35
+ # depends_on: resources, parameters or logical IDs that this resource is
36
+ # created after. condition: a condition of the stack, or its name.
37
+ # deletion_policy: and update_replace_policy: are Symbols or CloudFormation's
38
+ # names, and override what architecture §7 gives the type.
39
+ def initialize(scope, id, type:, properties: nil, depends_on: [], condition: nil, deletion_policy: nil, update_replace_policy: nil, metadata: {}, **opts)
40
+ unless scope.is_a?(Construct)
41
+ raise UsageError, "A resource is created in a Stack or in a Construct: #{id.inspect} got #{scope.inspect} as its scope"
42
+ end
43
+ host = scope.stack
44
+ unless host
45
+ raise UsageError, "A resource is created inside a Stack: #{id.inspect} is created in #{scope.path}, which has no Stack above it"
46
+ end
47
+
48
+ where = "resource #{id.inspect} in #{scope.path}"
49
+ @type = resource_type(type, where)
50
+ @properties = properties_hash(properties, opts, where)
51
+ # First occurrences kept, duplicates dropped: the CDK keeps dependencies
52
+ # in a Set (cfn-resource.ts:91, .add at :500), and its test expects one
53
+ # DependsOn entry after five adds of the same target.
54
+ @depends_on = Array(depends_on).map { |target| Core::Ids.logical_id_of(target, "#{where}: depends_on") }.uniq
55
+ @condition = Core::Ids.condition_name(condition, "#{where}: condition")
56
+ @deletion_policy = Core::Stateful.deletion_policy(deletion_policy, where:)
57
+ @update_replace_policy = Core::Stateful.update_replace_policy(update_replace_policy, where:)
58
+ unless metadata.is_a?(Hash)
59
+ raise UsageError, "#{where}: metadata takes a Hash, got #{metadata.inspect}"
60
+ end
61
+
62
+ @metadata = metadata.dup
63
+ # The logical ID has to be one CloudFormation takes, here and now: the
64
+ # ids from the Stack down to here, then this one. It is checked before
65
+ # the node joins the tree, so that a refused one leaves nothing behind.
66
+ logical_id = "#{Core::Ids.logical_id(scope)}#{Core::Ids.validate_id!(id, scope: scope)}"
67
+ Core::Ids.validate_logical_id!(logical_id, where: where)
68
+
69
+ super(scope, id)
70
+ @logical_id = logical_id
71
+ host.register_resource(self)
72
+ end
73
+
74
+ private
75
+
76
+ def resource_type(type, where)
77
+ return type if type.is_a?(String) && !type.empty?
78
+ return type.name if type.is_a?(Symbol) && !type.name.empty?
79
+
80
+ raise UsageError, "#{where}: the resource type must be a name such as AWS::S3::Bucket, got #{type.inspect}"
81
+ end
82
+
83
+ def properties_hash(properties, opts, where)
84
+ raise UsageError, "#{where}: #{BOTH_PROPERTIES}" if properties && !opts.empty?
85
+ unless properties.nil? || properties.is_a?(Hash)
86
+ raise UsageError, "#{where}: properties: takes a Hash, got #{properties.inspect}"
87
+ end
88
+
89
+ properties || opts
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "core"
4
+ require_relative "cfn/resource"
5
+
6
+ module RubyCdk
7
+ # The direct mapping to CloudFormation. Cfn is reserved for it, as in the CDK.
8
+ module Cfn
9
+ end
10
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Cli
5
+ # The words of a command line, before Thor reads them.
6
+ module Arguments
7
+ # The same words with the command first, when the options were written
8
+ # before it: `ruby-cdk --app app.rb deploy` is how the CDK CLI documents
9
+ # itself (`Usage: cdk -a <cdk-app> COMMAND`, cli.ts in aws-cdk-cli), and
10
+ # Thor only reads a command that comes first.
11
+ #
12
+ # commands are the words that name a command, with their aliases.
13
+ # switches are Thor's class options: an option that takes a value takes
14
+ # the word after it too, and that word may look like a command.
15
+ def self.command_first(argv, commands:, switches:)
16
+ words = argv.dup
17
+ index = 0
18
+ while (word = words[index])
19
+ return words unless word.start_with?("-") || commands.include?(word)
20
+ return [ words.delete_at(index), *words ] if commands.include?(word)
21
+ return words if word == "--"
22
+
23
+ index += 1 if takes_value?(word, switches)
24
+ index += 1
25
+ end
26
+ words
27
+ end
28
+
29
+ # --out DIR takes the next word; --out=DIR, --quiet and --no-color do not.
30
+ def self.takes_value?(word, switches)
31
+ return false if word.include?("=")
32
+
33
+ name = word.split("=", 2).first
34
+ option = switches.values.find do |candidate|
35
+ "--#{candidate.name}" == name || candidate.aliases.include?(name)
36
+ end
37
+ option && option.type != :boolean
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Cli
5
+ # The one place in the command line that asks the adapters for anything.
6
+ #
7
+ # It is an object, so that a test gives the command line another one and no
8
+ # client is ever built. Everything the command line knows about a region or
9
+ # a client it learns from here: resolving the region of a stack that names
10
+ # none (architecture section 13), and the clients of a region.
11
+ module Aws
12
+ # The region a client is built for when neither --region nor the stack's
13
+ # env names one: what the adapters read from the environment and from the
14
+ # profile's configuration. Raises RubyCdk::PreconditionError when nothing does.
15
+ def self.region(profile:, region:)
16
+ adapters
17
+ RubyCdk::Deploy::Sdk.resolve_region(profile: profile, region: region)
18
+ end
19
+
20
+ # The CloudFormation client and the object store of a region.
21
+ def self.clients(profile:, region:)
22
+ adapters
23
+ RubyCdk::Deploy::Sdk.clients(profile: profile, region: region)
24
+ end
25
+
26
+ # The adapters are loaded here, and only when a command needs a client,
27
+ # so that `version` and `synth` never load the AWS SDK (architecture
28
+ # principle 10).
29
+ def self.adapters
30
+ require_relative "../deploy/sdk_adapters"
31
+ end
32
+ private_class_method :adapters
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "failure"
4
+
5
+ module RubyCdk
6
+ module Cli
7
+ # `bootstrap`: the tool's asset bucket, deployed as the `ruby-cdk-bootstrap`
8
+ # stack through the bootstrap component (architecture section 8). There is
9
+ # no app file: the component builds the stack in an App of its own, with the
10
+ # env the command resolves. One stack, so deploy's selection does not apply.
11
+ #
12
+ # The target is who the credentials say (architecture section 13), printed
13
+ # by the engine before anything happens; --account given must be that
14
+ # account, checked here before anything is built, because an env is made of
15
+ # the resolved identity and the engine's own check would never fire.
16
+ module Bootstrap
17
+ # names are not taken: bootstrap is one stack.
18
+ def self.run(session)
19
+ region = session.options.region || session.aws.region(profile: session.options.profile, region: nil)
20
+ clients = session.aws.clients(profile: session.options.profile, region: region)
21
+ identity = session.identity(clients)
22
+ assert_account(session, identity)
23
+
24
+ app = RubyCdk::App.new(env: RubyCdk::Env.new(account: identity.account, region: region))
25
+ options = Deploy::DeployOptions.new(yes: !!session.options.yes, account: session.options.account,
26
+ profile: session.options.profile)
27
+
28
+ result = RubyCdk::Bootstrap.run(app:, clients:, output: session.output,
29
+ deployer_arn: session.options.deployer, options:)
30
+ print_json(session, result) if session.options.json
31
+ result.exit_code
32
+ end
33
+
34
+ # For --json, the one object on standard out, in the shape a deploy's
35
+ # records have, and nothing else there.
36
+ def self.print_json(session, result)
37
+ session.io.result("#{JSON.generate(
38
+ "name" => result.stack_name,
39
+ "stack_id" => result.stack_id,
40
+ "outcome" => result.outcome.to_s,
41
+ "exit_code" => result.exit_code,
42
+ "changes" => result.changes.map(&:to_h),
43
+ "outputs" => result.outputs
44
+ )}\n")
45
+ end
46
+
47
+ # --account is an assertion (architecture section 13): given, it must be
48
+ # the account the credentials resolve to, which is the account the
49
+ # bootstrap stack's env names. The engine would never see a mismatch,
50
+ # because the env is built from the identity; so the command checks.
51
+ def self.assert_account(session, identity)
52
+ wanted = session.options.account
53
+ return unless wanted && wanted.to_s != identity.account.to_s
54
+
55
+ Kernel.raise Usage.new("--account #{wanted} was given, but the credentials are for account #{identity.account}. " \
56
+ "Bootstrap deploys into the account the credentials name, and the asset bucket's name is made of it. " \
57
+ "Nothing was created.",
58
+ next_step: "Run `ruby-cdk bootstrap` again without --account, or with --account #{identity.account} " \
59
+ "if that is the account you mean (--profile NAME selects the credentials).")
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "failure"
5
+ require_relative "selection"
6
+
7
+ module RubyCdk
8
+ module Cli
9
+ # `diff`: the change preview of the stacks a deploy would deploy
10
+ # (architecture section 10).
11
+ #
12
+ # The stacks are chosen the way deploy chooses them (module Selection,
13
+ # read in packages/aws-cdk/lib/cli/cli.ts:800-819 in aws-cdk-cli at
14
+ # eca1b73d682d7763955bec30ab5dd52bbc4327b6): the app's only stack when
15
+ # nothing is named, a usage error otherwise, --all for every stack, a
16
+ # named stack bringing its dependencies unless --exclusively. Each stack
17
+ # is diffed against the template CloudFormation answers `get_template`
18
+ # with, through the port, and never through anything else: this command
19
+ # makes no other request, so it changes nothing.
20
+ #
21
+ # The CDK computes its diff through a change set, which is what tells it
22
+ # which properties replace a resource. Ours reads that from the schema
23
+ # model instead (architecture section 10), so diff makes no write-shaped
24
+ # request against the account at all.
25
+ #
26
+ # Output is text for a person on standard error -- where the CDK prints
27
+ # it too (its io host routes everything but result and error to standard
28
+ # error) -- and, with --json, one machine object per stack on standard
29
+ # output and nothing else there. The exit code is 0 with and without
30
+ # differences, the CDK's default; --fail makes a difference exit 1, as
31
+ # the CDK's --fail does. Under --security-only the CDK counts the stacks
32
+ # with security changes and nothing else, for the closing line and for
33
+ # the failure, and so does this command.
34
+ module Diff
35
+ def self.run(session, names)
36
+ manifest = session.manifest
37
+ session.say_synthesis_time
38
+ selected = Selection.choose(session.stacks, names:, all: session.options.all, command: "diff")
39
+ entries = Selection.ordered(manifest.entries, selected: selected.map(&:stack_name), direction: :up,
40
+ exclusively: session.options.exclusively)
41
+ announce_dependencies(session, selected, entries)
42
+ session.io.debug("diff: #{entries.map(&:name).join(", ")}")
43
+
44
+ security_only = !!session.options.security_only
45
+ diffs = entries.map { |entry| one(session, entry) }
46
+
47
+ if session.options.json
48
+ diffs.each do |diff|
49
+ session.io.result("#{JSON.generate(diff.to_h)}\n")
50
+ end
51
+ else
52
+ diffs.each do |diff|
53
+ text = RubyCdk::Diff.render(diff, quiet: !!session.options.quiet, security_only: security_only)
54
+ session.io.say(text.chomp) unless text.empty?
55
+ end
56
+ session.io.say(summary(counted(diffs, security_only)))
57
+ end
58
+
59
+ session.options.fail && counted(diffs, security_only).positive? ? 1 : Cli::SUCCESS
60
+ end
61
+
62
+ # The CDK's closing line (cdk-toolkit.ts, `Number of stacks with
63
+ # differences`): how many stacks change, not how many resources.
64
+ def self.summary(count)
65
+ "✨ Number of stacks with differences: #{count}"
66
+ end
67
+
68
+ # One stack, from synthesis's output to its diff.
69
+ def self.one(session, entry)
70
+ stack = session.stack(entry.name)
71
+ region = session.region_of(stack)
72
+ clients = session.clients(region:)
73
+ session.io.debug("#{entry.name}: region #{region}#{session.region_source(stack)}")
74
+ RubyCdk::Diff.for_stack(clients.cfn, entry.name, template: session.template_of(entry))
75
+ end
76
+
77
+ # The CDK deploys a named stack's dependencies and says so (cli.ts:821-839,
78
+ # expandUp); a diff reads them too, since deploying the stack would.
79
+ def self.announce_dependencies(session, selected, entries)
80
+ return if session.options.all || session.options.exclusively
81
+
82
+ extra = entries.map(&:name) - selected.map(&:stack_name)
83
+ return if extra.empty?
84
+
85
+ session.io.say("Including dependency stacks: #{extra.join(", ")}")
86
+ end
87
+
88
+ def self.counted(diffs, security_only)
89
+ if security_only
90
+ diffs.count { |diff| diff.security.has_changes? }
91
+ else
92
+ diffs.count { |diff| !diff.empty? }
93
+ end
94
+ end
95
+ private_class_method :counted
96
+ end
97
+ end
98
+ end