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,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Cli
5
+ # Prints what a command ended with and answers its exit code (architecture
6
+ # section 14). The exit code is the error's class, never its message:
7
+ # RubyCdk::Deploy.exit_code_for decides, and the command line adds nothing
8
+ # to it except its own usage errors, which are 1.
9
+ #
10
+ # Every failure ends with the line that names the command to run next. The
11
+ # engine's errors already carry theirs in their message; the command line's
12
+ # own carry it in Cli::Usage#next_step; and an app file that raised says
13
+ # which file to correct and which command to run again.
14
+ def self.report(error, io:, command:)
15
+ case error
16
+ when AppFileError
17
+ app_file(error, io, command)
18
+ when Usage
19
+ io.failure("ruby-cdk: #{error.message}")
20
+ io.say(error.next_step) if error.next_step
21
+ USAGE
22
+ when RubyCdk::ValidationError
23
+ io.failure(text(error))
24
+ io.say("Correct the template and run `ruby-cdk #{command}` again.")
25
+ Deploy.exit_code_for(error)
26
+ when RubyCdk::Error
27
+ approval(error, io, command)
28
+ Deploy.exit_code_for(error)
29
+ when ->(error) { credential_failure?(error) }
30
+ # An AWS credential or SSO failure (InvalidSSOToken, an expired token, a
31
+ # profile that cannot refresh): a precondition of the run, not a bug.
32
+ # The SDK's message is printed first; the command to run next is ours.
33
+ io.failure("ruby-cdk: #{text(error)}")
34
+ io.say("The AWS session or the credentials are not usable. Run `aws sso login --profile PROFILE` " \
35
+ "(or refresh the credentials another way), then run the command again.")
36
+ USAGE
37
+ when Thor::Error
38
+ # Thor's own usage errors: an unknown command, an unknown option, an
39
+ # option without its value. The commands named there, when there is
40
+ # one, are what the help should be asked about; `help` and its flags
41
+ # are no command of this tool's.
42
+ io.failure("ruby-cdk: #{error.message}")
43
+ about = command && command != "help" && !%w[-h -? --help -D].include?(command) ? " #{command}" : ""
44
+ io.say("Run `ruby-cdk help#{about}` to see what #{about.empty? ? "the commands are" : "it takes"}.")
45
+ USAGE
46
+ else
47
+ io.failure("ruby-cdk: #{error.class}: #{text(error)}")
48
+ io.failure("This is not a failure the command line knows how to explain, so nothing more can be said " \
49
+ "about what the command did before it.")
50
+ io.say(error.backtrace.join("\n")) if io.verbose && error.backtrace
51
+ io.failure("Report it as a bug in ruby-cdk, with the command and this output.")
52
+ USAGE
53
+ end
54
+ end
55
+
56
+ # An app file that raised (architecture section 11): the class, the message
57
+ # and the first frame that is in the file. The gem's backtrace only with --verbose.
58
+ def self.app_file(error, io, command)
59
+ if error.gem_error?
60
+ io.failure("ruby-cdk: #{text(error.error)}")
61
+ io.say(" at #{error.path}: #{error.location}") if error.location
62
+ else
63
+ io.failure("#{error.path}: #{error.location || "no line of it raised it; the failure came from what it loaded"}")
64
+ io.failure("#{error.error.class}: #{text(error.error)}")
65
+ end
66
+ io.say(error.backtrace.join("\n")) if io.verbose
67
+ io.say("Correct #{error.path} and run `ruby-cdk #{command}` again.")
68
+ USAGE
69
+ end
70
+
71
+ # An error's message, as text a terminal takes: an app file can raise with
72
+ # bytes in its message that are not UTF-8.
73
+ def self.text(error)
74
+ error.message.to_s.encode("UTF-8", invalid: :replace, undef: :replace)
75
+ end
76
+
77
+ # True for the AWS errors that mean "the session or the credentials cannot
78
+ # be used". Matched on the error class's name — the SDK raises a distinct
79
+ # class for each of these failures (InvalidSSOToken, InvalidSSOCredentials,
80
+ # MissingCredentialsError, the services' ExpiredToken and
81
+ # InvalidClientTokenId...) — and on the two message shapes that have no
82
+ # class of their own: the signature failure and the instance metadata
83
+ # endpoint probed in vain. Nothing Aws:: is loaded to ask. An unrelated AWS
84
+ # error whose message happens to contain "Token" or "SSO" — a
85
+ # CloudFormation or IAM validation message, say — is not classified here.
86
+ CREDENTIAL_CLASS = /
87
+ InvalidSSOToken|InvalidSSOCredentials|SSOError|InvalidLoginToken|
88
+ TokenRefreshRequired|ExpiredToken|InvalidClientTokenId|
89
+ MissingCredentialsError|MissingBearerTokenError|MissingWebIdentityTokenFile|
90
+ NoSourceCredentialsError|InvalidCredentialSourceError|CredentialSourceConflictError
91
+ /x.freeze
92
+ CREDENTIAL_MESSAGE = /unable to sign request|Failed to open TCP connection to 169\.254/.freeze
93
+
94
+ def self.credential_failure?(error)
95
+ return false unless error.class.name.start_with?("Aws::")
96
+
97
+ CREDENTIAL_CLASS.match?(error.class.name) || CREDENTIAL_MESSAGE.match?(text(error))
98
+ end
99
+
100
+ # An approval that was not given (exit 4). When nobody could have given it,
101
+ # because no terminal is attached to answer, the CDK refuses with what is
102
+ # missing and the two ways out, and that shape is what a person needs
103
+ # (packages/aws-cdk/lib/cli/user-input.ts in aws-cdk-cli, the prompt's
104
+ # refusal). What was already made is named as it is: the engine deletes a
105
+ # change set that was refused, and deletes the stack a creation made
106
+ # (architecture section 9, housekeeping). In a terminal it was a decision:
107
+ # the engine's own message says so, and carries the stack and what it left.
108
+ def self.approval(error, io, command)
109
+ if error.is_a?(Deploy::ApprovalRequired) && !io.interactive?
110
+ done = command == "destroy" ? "nothing was deleted" : "nothing was deployed"
111
+ io.failure("ruby-cdk: No terminal is attached to answer the question, so the command stopped, and #{done}.")
112
+ io.say("Run `ruby-cdk #{command}` again with --yes to do it without the question, or run it in a terminal to answer it.")
113
+ else
114
+ io.failure(text(error))
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "failure"
5
+ require_relative "pairs"
6
+
7
+ module RubyCdk
8
+ module Cli
9
+ # Which stacks a command acts on, and in what order. The CDK's rules, read
10
+ # in aws/aws-cdk-cli at eca1b73d682d7763955bec30ab5dd52bbc4327b6:
11
+ #
12
+ # - No name is the app's only stack when the app has exactly one, and a
13
+ # usage error otherwise, in the CDK's words. It is `explicitOrDefaultStacks`
14
+ # with `StackSelectionStrategy.ONLY_SINGLE` (packages/aws-cdk/lib/cli/cli.ts:800-819)
15
+ # and the message of `multipleStacksWithoutSelectorMessage`
16
+ # (packages/@aws-cdk/toolkit-lib/lib/api/cloud-assembly/private/stack-assembly.ts:386-404).
17
+ # - `--all` is every stack, and `--all` with names is an error (cli.ts:292-294).
18
+ # - A deploy brings the dependencies of the stacks it names, and a destroy
19
+ # the stacks that depend on them, unless `--exclusively` (cli.ts:821-839).
20
+ # A deploy goes dependencies first, a destroy dependents first.
21
+ #
22
+ # Two things are decided here against the CDK, and recorded with the reason:
23
+ #
24
+ # - Names are exact. The CDK also takes globs and `!` patterns; they are not
25
+ # ported in this wave, and a stack's name is known (`ruby-cdk ls`).
26
+ # - A name that is no stack's is always an error. For a deploy that is the
27
+ # CDK's own `PATTERN_MUST_MATCH` (stack-assembly.ts:184-190). For a destroy
28
+ # the CDK treats a pattern that matches nothing as nothing to do
29
+ # (cli.ts:607-608); here it is an error too, because an exit code of 0
30
+ # after a mistyped name would tell a script that the stack is gone. The
31
+ # same for a name among others that do match, where the CDK deploys the
32
+ # ones that match and says nothing of the rest.
33
+ #
34
+ # A circle of dependencies never reaches this module: the tree refuses one
35
+ # as it is built. The check below stays, as a backstop that names the circle.
36
+ module Selection
37
+ # The stacks a command acts on, among stacks, from the names it was given
38
+ # and --all, in the order the app holds them. Raises Cli::Usage. command is
39
+ # "deploy" or "destroy", for the line that says what to run next.
40
+ def self.choose(stacks, names:, all:, command:)
41
+ names = names.compact
42
+ if names.any? && all
43
+ Kernel.raise Usage.new("You must either specify a list of Stacks or the `--all` argument",
44
+ next_step: "Run `ruby-cdk #{command} #{names.join(" ")}`, or `ruby-cdk #{command} --all`.")
45
+ end
46
+ return stacks.dup if all
47
+
48
+ if names.empty?
49
+ unless stacks.one?
50
+ Kernel.raise Usage.new(no_single(stacks),
51
+ next_step: "Run `ruby-cdk #{command} --all`, or `ruby-cdk #{command} STACK` for one of them.")
52
+ end
53
+
54
+ return stacks.dup
55
+ end
56
+
57
+ missing = names.uniq - stacks.map(&:stack_name)
58
+ unless missing.empty?
59
+ Kernel.raise Usage.new("No stacks match the name(s) #{missing.join(", ")}",
60
+ next_step: "Run `ruby-cdk ls` to see the stacks of the app, then `ruby-cdk #{command} STACK`.")
61
+ end
62
+ stacks.select { |stack| names.include?(stack.stack_name) }
63
+ end
64
+
65
+ # The entries to act on: the selected stacks, with what they need and in
66
+ # the order that works. direction is :up for a deploy, which needs a
67
+ # stack's dependencies first, and :down for a destroy, which needs the
68
+ # stacks that depend on it first. exclusively leaves the others alone.
69
+ def self.ordered(entries, selected:, direction:, exclusively:)
70
+ needed = exclusively ? selected.dup : closure(entries, selected, direction)
71
+ sorted = dependencies_first(entries)
72
+ sorted.reverse! if direction == :down
73
+ sorted.select { |entry| needed.include?(entry.name) }
74
+ end
75
+
76
+ # The CDK's message when no stack was named and the app has more than one,
77
+ # without the part about wildcards: they are not ported.
78
+ def self.no_single(stacks)
79
+ return "This app contains no stacks" if stacks.empty?
80
+
81
+ "Since this app includes more than a single stack, specify which stacks to use or specify `--all`\n" \
82
+ "Stacks: #{stacks.map(&:stack_name).join(" · ")}"
83
+ end
84
+
85
+ # Every entry, each after the ones it depends on. Raises Cli::Usage when
86
+ # the dependencies form a circle, naming it.
87
+ def self.dependencies_first(entries)
88
+ by_name = entries.to_h { |entry| [ entry.name, entry ] }
89
+ placed = {}
90
+ order = []
91
+ entries.each { |entry| place(entry.name, [], by_name, placed, order) }
92
+ order
93
+ end
94
+
95
+ # The walk behind dependencies_first. trail is the stack's path here, so
96
+ # that a circle is named by the road that led to it.
97
+ def self.place(name, trail, by_name, placed, order)
98
+ if trail.include?(name)
99
+ Kernel.raise Usage, "The stacks depend on each other in a circle: #{(trail + [ name ]).join(" -> ")}"
100
+ end
101
+ entry = by_name[name]
102
+ return if entry.nil? || placed[name]
103
+
104
+ placed[name] = true
105
+ Array(entry.dependencies).each { |dependency| place(dependency, trail + [ name ], by_name, placed, order) }
106
+ order << entry
107
+ end
108
+ private_class_method :place
109
+
110
+ # The names of the selected stacks and of everything they need in direction.
111
+ def self.closure(entries, selected, direction)
112
+ edges =
113
+ if direction == :up
114
+ entries.to_h { |entry| [ entry.name, entry.dependencies ] }
115
+ else
116
+ dependents = Hash.new { |hash, key| hash[key] = [] }
117
+ entries.each { |entry| Array(entry.dependencies).each { |dependency| dependents[dependency] << entry.name } }
118
+ dependents
119
+ end
120
+
121
+ needed = {}
122
+ frontier = selected.dup
123
+ until frontier.empty?
124
+ name = frontier.pop
125
+ next if needed[name]
126
+
127
+ needed[name] = true
128
+ frontier.concat(Array(edges[name]))
129
+ end
130
+ needed.keys
131
+ end
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,290 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../schema/validator"
5
+ require_relative "failure"
6
+ require_relative "pairs"
7
+
8
+ module RubyCdk
9
+ module Cli
10
+ # What one run of a command has: its options, its streams, the app file's
11
+ # App once it is loaded, and the one object that builds AWS clients.
12
+ #
13
+ # Everything here hands over to a component: App.build! loads the app file,
14
+ # App#synth writes the templates, the adapters resolve a region and build
15
+ # the clients, the engine deploys. The session keeps what was asked for and
16
+ # refuses, before anything runs, what cannot be used.
17
+ class Session
18
+ # Every option a command may take, as Thor parsed it. An option the
19
+ # command does not take, or that was not given, is nil; a boolean that
20
+ # was given is true.
21
+ Options = Data.define(:app, :out, :profile, :region, :account, :yes, :force, :quiet, :verbose, :json, :color,
22
+ :long, :all, :exclusively, :execute, :on_failure, :parameters, :tags, :outputs_file,
23
+ :no_validate, :strict_types, :deployer, :fail, :security_only)
24
+
25
+ # Thor's options as Options.
26
+ def self.options_from(given)
27
+ Options.new(**Options.members.to_h { |name| [ name, given[name] ] })
28
+ end
29
+
30
+ attr_reader :command, :options, :io, :aws
31
+
32
+ def initialize(command:, options:, io:, aws:)
33
+ @command = command
34
+ @options = options
35
+ @io = io
36
+ @aws = aws
37
+ @clients = {}
38
+ @identities = {}
39
+ check_paths
40
+ end
41
+
42
+ # The App the app file created, loaded once. Architecture section 11: the
43
+ # file must create exactly one RubyCdk::App, and --out reaches an App the
44
+ # file created without an out_dir of its own.
45
+ def app
46
+ @app ||= begin
47
+ path = File.expand_path(options.app.to_s)
48
+ unless File.file?(path)
49
+ raise Usage.new("There is no app file at #{path}",
50
+ next_step: "Run the command from the app's directory, or with --app PATH (the default is cdk.rb).")
51
+ end
52
+
53
+ io.debug("loading the app file #{path}")
54
+ load_app(path)
55
+ end
56
+ end
57
+
58
+ # Synthesis (architecture section 5), once: the templates are written and
59
+ # the manifest answered. Raises RubyCdk::ValidationError when a rule fails.
60
+ # The time it took is kept, for the line the CDK prints after it
61
+ # (cdk-toolkit.ts in aws-cdk-cli: "Synthesis time: 4.43s").
62
+ def manifest
63
+ @manifest ||= begin
64
+ started = clock
65
+ synth_app.tap { @synthesis_seconds = clock - started }
66
+ end
67
+ end
68
+
69
+ # --no-validate asks the pipeline to skip the schema rules: the tree's own
70
+ # rules (V2, V13) still run, and the report command is how the rules are
71
+ # seen without writing. The pipeline is asked with App#synth(validate:).
72
+ # Until the pipeline takes the keyword (the core track is adding it), the
73
+ # flag says so under --verbose and the validators still run: this method
74
+ # flips to the keyword the moment the pipeline accepts it, and the call
75
+ # above is the only place that changes.
76
+ def synth_app
77
+ return app.synth(validate: false) if options.no_validate && pipeline_takes_validate?
78
+
79
+ io.debug("--no-validate: the pipeline does not take validate: yet, so the schema rules still ran") if options.no_validate
80
+ app.synth
81
+ end
82
+
83
+ # The types architecture section 7 retains, as V15 is built with.
84
+ def stateful_types
85
+ Core::Stateful::RETAINED_TYPES + Core::Stateful::SNAPSHOT_TYPES
86
+ end
87
+
88
+ # --strict-types: the validators are registered once at umbrella load, so
89
+ # strictness is a re-registration. Everything the umbrella registered is
90
+ # taken out, and the same list built with strict_types: true goes in. The
91
+ # pipeline's own V2 and V13 are left alone: the tree registers those
92
+ # itself, and they were never taken out. Nothing is restored: a process
93
+ # runs one command.
94
+ def register_strict_validators
95
+ return if @strict_registered
96
+
97
+ RubyCdk::Synth.validators.each do |validator|
98
+ next if validator.is_a?(RubyCdk::Synth::Rules::LogicalIds) || validator.is_a?(RubyCdk::Synth::Rules::StackName)
99
+
100
+ RubyCdk::Synth.unregister_validator(validator)
101
+ end
102
+ RubyCdk::Validation.validators(strict_types: true, warnings: true, stateful_types: stateful_types)
103
+ .each { |validator| RubyCdk::Synth.register_validator(validator) }
104
+ @strict_registered = true
105
+ io.debug("validators re-registered with strict_types: V1 makes an unknown type an error")
106
+ end
107
+
108
+ # The pipeline's warnings, once the pipeline carries them apart (the core
109
+ # track is adding the list, and the manifest is what synthesize_app hands
110
+ # over). Nothing under --quiet or --json, like the synthesis-time line.
111
+ def say_warnings(manifest)
112
+ return if options.quiet || options.json
113
+ return unless manifest.respond_to?(:warnings)
114
+
115
+ Array(manifest.warnings).each do |warning|
116
+ io.say("warning #{warning.rule} #{warning.path}: #{warning.message}")
117
+ end
118
+ end
119
+
120
+ # How long the one synthesis took, in seconds.
121
+ def synthesis_seconds
122
+ @synthesis_seconds
123
+ end
124
+
125
+ # The line after a synthesis, for a person. The CDK prints it after every
126
+ # synthesis (cdk-toolkit.ts:522-523); it is silent for --quiet and --json,
127
+ # which both keep the stream whole.
128
+ def say_synthesis_time
129
+ io.say(format("Synthesis time: %.2fs", synthesis_seconds)) unless options.quiet || options.json
130
+ end
131
+
132
+ def stacks
133
+ app.stacks
134
+ end
135
+
136
+ def stack(name)
137
+ stacks.find { |candidate| candidate.stack_name == name }
138
+ end
139
+
140
+ # The bytes of a stack's template, as they were written.
141
+ def template_of(entry)
142
+ File.binread(File.join(manifest.out_dir, entry.template))
143
+ end
144
+
145
+ # The region of a stack (architecture section 13): --region, else the
146
+ # stack's env, else what the adapters resolve for the profile. The engine
147
+ # refuses a stack whose env says otherwise.
148
+ def region_of(stack)
149
+ return options.region if options.region
150
+ return stack.env.region if stack.env
151
+
152
+ @region ||= aws.region(profile: options.profile, region: nil)
153
+ end
154
+
155
+ # Where region_of found it, for --verbose.
156
+ def region_source(stack)
157
+ if options.region
158
+ " (--region)"
159
+ elsif stack.env
160
+ " (the stack's env)"
161
+ else
162
+ " (resolved for #{options.profile ? "profile #{options.profile}" : "the default credentials"})"
163
+ end
164
+ end
165
+
166
+ # The clients of a region, built once per region.
167
+ def clients(region:)
168
+ @clients[region] ||= aws.clients(profile: options.profile, region: region)
169
+ end
170
+
171
+ # Who the credentials are, asked of the client once per region.
172
+ def identity(clients)
173
+ @identities[clients.object_id] ||= clients.cfn.resolve_identity
174
+ end
175
+
176
+ # The engine, with the output object the options select: Json for --json,
177
+ # Quiet for --quiet, Human otherwise, which is also what --verbose gets.
178
+ # The publisher is what a template too large for a request uses: it goes
179
+ # into the stack's asset bucket and the change set carries its URL (§8).
180
+ def deployer(clients)
181
+ Deploy::Deployer.new(client: clients.cfn, store: clients.store, output: output,
182
+ template_publisher: lambda { |stack, template|
183
+ Assets.publish_template(stack, template, store: clients.store, owner: identity(clients).account)
184
+ })
185
+ end
186
+
187
+ # What the engine is given for a deploy.
188
+ def deploy_options
189
+ @deploy_options ||= Deploy::DeployOptions.new(
190
+ parameters: Pairs.parse(options.parameters, option: "--parameters", command:),
191
+ tags: Pairs.parse(options.tags, option: "--tags", command:),
192
+ yes: !!options.yes,
193
+ no_execute: options.execute == false,
194
+ on_failure: on_failure,
195
+ outputs_file: outputs_file,
196
+ account: options.account,
197
+ force: !!options.force,
198
+ profile: options.profile
199
+ )
200
+ end
201
+
202
+ # What the engine is given for a destroy. --yes skips the confirmation, as
203
+ # architecture section 9 says, and so does --force, which is the CDK's own
204
+ # flag for it (parse-command-line-arguments.ts:924-927 in aws-cdk-cli).
205
+ def destroy_options
206
+ @destroy_options ||= Deploy::DeployOptions.new(
207
+ yes: !!options.yes || !!options.force,
208
+ account: options.account,
209
+ profile: options.profile
210
+ )
211
+ end
212
+
213
+ # The engine's output object, on the session's streams.
214
+ def output
215
+ @output ||=
216
+ if options.json
217
+ Deploy::Output::Json.new(io: io.err, stdin: io.stdin, result_io: io.err)
218
+ elsif options.quiet
219
+ Deploy::Output::Quiet.new(io: io.err, stdin: io.stdin, result_io: io.out)
220
+ else
221
+ Deploy::Output::Human.new(io: io.err, stdin: io.stdin, result_io: io.out, color: io.color)
222
+ end
223
+ end
224
+
225
+ private
226
+
227
+ def clock
228
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
229
+ end
230
+
231
+ # True when the pipeline's synth takes the validate keyword.
232
+ def pipeline_takes_validate?
233
+ app.method(:synth).parameters.any? { |_kind, name| name == :validate }
234
+ end
235
+
236
+ # The app file, or the error placed where it happened.
237
+ def load_app(path)
238
+ App.build!(app_file: path, out_dir: options.out)
239
+ rescue RubyCdk::Error => e
240
+ # One of this gem's errors raised by the app file: it is already written
241
+ # for a user, and it is still placed at the file's line.
242
+ raise AppFileError.new(path, e) if AppFileError::Location.in(path, e)
243
+
244
+ raise
245
+ rescue ScriptError, StandardError => e
246
+ raise AppFileError.new(path, e)
247
+ end
248
+
249
+ # --app, --out, --profile, --region and --account name something when they are given.
250
+ def check_paths
251
+ { app: "--app", out: "--out", profile: "--profile", region: "--region", account: "--account" }.each do |name, option|
252
+ value = options.public_send(name)
253
+ next unless value && value.to_s.strip.empty?
254
+
255
+ raise Usage.new("#{option} must not be empty", next_step: "Run `ruby-cdk #{command}` again without #{option}, or with #{option} VALUE.")
256
+ end
257
+ end
258
+
259
+ # --on-failure, checked against the engine's own table before any request,
260
+ # so that a typo is a usage error and not a failed deploy.
261
+ def on_failure
262
+ wanted = options.on_failure.to_s
263
+ unless Deploy::Deployer::ON_FAILURE.key?(wanted.downcase)
264
+ raise Usage.new("--on-failure must be one of DELETE, ROLLBACK or DO_NOTHING, not #{wanted.inspect}",
265
+ next_step: "Run `ruby-cdk #{command}` again with --on-failure DELETE.")
266
+ end
267
+
268
+ wanted
269
+ end
270
+
271
+ # --outputs-file, checked before any request: the engine writes it after a
272
+ # deploy succeeded, and a path it cannot write to must not be found then.
273
+ def outputs_file
274
+ path = options.outputs_file
275
+ return nil unless path
276
+
277
+ if path.strip.empty?
278
+ raise Usage.new("--outputs-file must not be empty", next_step: "Run `ruby-cdk #{command}` again with --outputs-file PATH.")
279
+ end
280
+ directory = File.dirname(File.expand_path(path))
281
+ unless File.directory?(directory)
282
+ raise Usage.new("The directory of --outputs-file does not exist: #{directory}",
283
+ next_step: "Create it, or run `ruby-cdk #{command}` again with --outputs-file PATH in a directory that exists.")
284
+ end
285
+
286
+ path
287
+ end
288
+ end
289
+ end
290
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Cli
5
+ # Thor's shell, writing to the streams the command line was given instead
6
+ # of the real ones, so that help and usage errors are read by a test like
7
+ # any other output. It is the plain shell: nothing the command line prints
8
+ # through Thor carries colour, whatever --no-color says.
9
+ #
10
+ # It also carries what the edge was given, for the commands to build their
11
+ # session from: the streams, and the one object that builds AWS clients.
12
+ class Shell < Thor::Shell::Basic
13
+ attr_reader :io, :aws
14
+
15
+ def initialize(io, aws)
16
+ super()
17
+ @io = io
18
+ @aws = aws
19
+ end
20
+
21
+ def stdout
22
+ io.out
23
+ end
24
+
25
+ def stderr
26
+ io.err
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "failure"
5
+ require_relative "pairs"
6
+
7
+ module RubyCdk
8
+ module Cli
9
+ # `synth`: every phase of architecture section 5 on every stack of the app,
10
+ # which writes the templates and the manifest, and then the template on
11
+ # standard out.
12
+ #
13
+ # What is printed is the CDK's synth (packages/aws-cdk/lib/cli/cdk-toolkit.ts:1123-1165
14
+ # in aws-cdk-cli at eca1b73d682d7763955bec30ab5dd52bbc4327b6): one stack,
15
+ # or one named, has its template on standard out unless --quiet; several
16
+ # stacks put nothing there and say why on standard error. This tool writes
17
+ # JSON only, so the CDK's `--json` (JSON instead of YAML) is something else
18
+ # here: the content of the manifest, on standard out.
19
+ module Synth
20
+ # names are the STACK words: the template of the one stack named is the
21
+ # one printed. Answers the exit code.
22
+ def self.run(session, names)
23
+ manifest = session.manifest
24
+ session.say_synthesis_time
25
+ session.say_warnings(manifest)
26
+ entries = named(manifest.entries, names, session)
27
+ io = session.io
28
+ io.debug("synthesized #{manifest.entries.length} stack(s) into #{File.expand_path(manifest.out_dir)}")
29
+
30
+ if session.options.json
31
+ io.result(manifest.bytes)
32
+ elsif !session.options.quiet && entries.one?
33
+ io.result(session.template_of(entries.first))
34
+ end
35
+ return Cli::SUCCESS if session.options.json
36
+
37
+ if names.empty? && manifest.entries.length > 1
38
+ io.say("Successfully synthesized to #{File.expand_path(manifest.out_dir)}")
39
+ io.say("Supply a stack id (#{manifest.entries.map(&:name).join(", ")}) to display its template.")
40
+ end
41
+ Cli::SUCCESS
42
+ end
43
+
44
+ # The entries the names stand for; every entry when none was given.
45
+ def self.named(entries, names, session)
46
+ names = names.compact
47
+ return entries if names.empty?
48
+
49
+ missing = names - entries.map(&:name)
50
+ unless missing.empty?
51
+ Kernel.raise Usage.new("No stacks match the name(s) #{missing.join(", ")}",
52
+ next_step: "Run `ruby-cdk ls` to see the stacks of the app, then `ruby-cdk synth STACK`.")
53
+ end
54
+ entries.select { |entry| names.include?(entry.name) }
55
+ end
56
+ end
57
+ end
58
+ end