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,322 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "statement"
4
+
5
+ module RubyCdk
6
+ module Diff
7
+ # The security view of a diff (architecture section 10): the IAM
8
+ # statements a deployment adds or takes away, and the managed policies it
9
+ # attaches, in a table of their own, with the capabilities the new
10
+ # template needs that the deployed one did not.
11
+ #
12
+ # The CDK's view is a heuristic: it reads a property only where AWS's
13
+ # service metadata says the property may carry a policy, and warns for it
14
+ # ("There may be security-related changes not in this list", its issue
15
+ # 1299). Ours is exact by resource type and by the statements the template
16
+ # carries: every resource of both templates is walked for the property
17
+ # names that carry policy documents anywhere AWS publishes one, so a
18
+ # statement cannot hide in a type the metadata does not mention. That is
19
+ # the one line the command's help says it with.
20
+ class Security
21
+ # The property names that carry an IAM policy document, wherever AWS
22
+ # publishes one: identity policies, resource policies, trust policies,
23
+ # key policies, repository and domain access policies alike.
24
+ POLICY_PROPERTIES = %w[PolicyDocument AssumeRolePolicyDocument KeyPolicy RepositoryPolicyText AccessPolicies].freeze
25
+
26
+ # The identities whose inline Policies carry statements that apply to
27
+ # the identity itself.
28
+ IDENTITY_TYPES = %w[
29
+ AWS::IAM::Role
30
+ AWS::IAM::User
31
+ AWS::IAM::Group
32
+ ].freeze
33
+
34
+ # The resource types whose one job is a policy attached to another
35
+ # resource: the statement's resource is the sibling property that names
36
+ # it.
37
+ ATTACHED_POLICY_TYPES = %w[
38
+ AWS::S3::BucketPolicy
39
+ AWS::SQS::QueuePolicy
40
+ AWS::SNS::TopicPolicy
41
+ ].freeze
42
+
43
+ # The types CloudFormation refuses a change set without a capability
44
+ # for, and the properties that name an IAM resource explicitly. The same
45
+ # eight types and five names deploy reads (deploy/capabilities.rb, both
46
+ # from CloudFormation's change-set reference): the diff component reads a
47
+ # table of its own, because the engine is not among its dependencies.
48
+ CAPABILITY_TYPES = %w[
49
+ AWS::IAM::AccessKey
50
+ AWS::IAM::Group
51
+ AWS::IAM::InstanceProfile
52
+ AWS::IAM::ManagedPolicy
53
+ AWS::IAM::Policy
54
+ AWS::IAM::Role
55
+ AWS::IAM::User
56
+ AWS::IAM::UserToGroupAddition
57
+ ].freeze
58
+ NAME_PROPERTIES = %w[RoleName ManagedPolicyName UserName GroupName InstanceProfileName].freeze
59
+
60
+ # One managed policy attachment: an identity, and the ARN attached to it.
61
+ Attachment = Data.define(:identity, :arn) do
62
+ def equal?(other)
63
+ identity == other.identity && arn == other.arn
64
+ end
65
+
66
+ def to_h
67
+ { "identity" => identity, "arn" => arn }
68
+ end
69
+ end
70
+
71
+ # The statements of each side of the diff: additions are the ones the new
72
+ # template carries that the deployed one does not, removals the reverse.
73
+ # Managed policies the same, as attachments of an identity to an ARN.
74
+ attr_reader :statement_additions, :statement_removals, :managed_policy_additions, :managed_policy_removals
75
+ attr_reader :capabilities_added
76
+
77
+ def self.build(diff)
78
+ statements_old = []
79
+ statements_new = []
80
+ policies_old = []
81
+ policies_new = []
82
+
83
+ diff.resources.each_value do |change|
84
+ statements_old.concat(change_statements(change, :old))
85
+ statements_new.concat(change_statements(change, :new))
86
+ policies_old.concat(managed_policies(change, :old))
87
+ policies_new.concat(managed_policies(change, :new))
88
+ end
89
+
90
+ capabilities = capability_set(diff_resources(diff, :new)) - capability_set(diff_resources(diff, :old))
91
+ new(statement_additions: added(statements_new, statements_old), statement_removals: added(statements_old, statements_new),
92
+ managed_policy_additions: added(policies_new, policies_old), managed_policy_removals: added(policies_old, policies_new),
93
+ capabilities_added: capabilities)
94
+ end
95
+
96
+ def initialize(statement_additions:, statement_removals:, managed_policy_additions:, managed_policy_removals:, capabilities_added:)
97
+ @statement_additions = statement_additions.freeze
98
+ @statement_removals = statement_removals.freeze
99
+ @managed_policy_additions = managed_policy_additions.freeze
100
+ @managed_policy_removals = managed_policy_removals.freeze
101
+ @capabilities_added = capabilities_added.freeze
102
+ end
103
+
104
+ def has_changes?
105
+ statement_additions.any? || statement_removals.any? || managed_policy_additions.any? ||
106
+ managed_policy_removals.any? || capabilities_added.any?
107
+ end
108
+
109
+ # True when the deployment widens what the deployed template may do, the
110
+ # CDK's permissionsBroadened: a positive statement granted, a negative
111
+ # one taken away, a managed policy attached.
112
+ def broadening?
113
+ statement_additions.any? { |statement| !statement.negative? } ||
114
+ statement_removals.any?(&:negative?) ||
115
+ managed_policy_additions.any?
116
+ end
117
+
118
+ # True when the change of this resource is one the security view owns: a
119
+ # capability-affecting type, a policy document it carries, or a managed
120
+ # policy it attaches, on either side of the diff.
121
+ def security_change?(change)
122
+ [ change.old_type, change.new_type ].compact.any? { |type| CAPABILITY_TYPES.include?(type) } ||
123
+ change.old_type == "AWS::Lambda::Permission" || change.new_type == "AWS::Lambda::Permission" ||
124
+ self.class.properties_of(change, :old)&.key?("ManagedPolicyArns") ||
125
+ self.class.properties_of(change, :new)&.key?("ManagedPolicyArns") ||
126
+ self.class.watched_property?(self.class.properties_of(change, :old)) ||
127
+ self.class.watched_property?(self.class.properties_of(change, :new))
128
+ end
129
+
130
+ # The whole view for --json.
131
+ def to_h
132
+ {
133
+ "broadening" => broadening?,
134
+ "has_changes" => has_changes?,
135
+ "capabilities_added" => capabilities_added,
136
+ "statements" => {
137
+ "additions" => statement_additions.map(&:to_h),
138
+ "removals" => statement_removals.map(&:to_h)
139
+ },
140
+ "managed_policies" => {
141
+ "additions" => managed_policy_additions.map(&:to_h),
142
+ "removals" => managed_policy_removals.map(&:to_h)
143
+ }
144
+ }
145
+ end
146
+
147
+ # --- the walk that finds what a template carries
148
+
149
+ # The statements of one side of one resource's change.
150
+ def self.change_statements(change, side)
151
+ type = side == :old ? change.old_type : change.new_type
152
+ properties = properties_of(change, side)
153
+ return [] if type.nil? || !properties.is_a?(Hash)
154
+
155
+ read_statements(type, properties, change.logical_id)
156
+ end
157
+
158
+ def self.managed_policies(change, side)
159
+ properties = properties_of(change, side)
160
+ return [] unless properties.is_a?(Hash) && properties.key?("ManagedPolicyArns")
161
+
162
+ arns = RenderIntrinsics.call(properties["ManagedPolicyArns"])
163
+ Array(arns).map { |arn| Attachment.new(identity: "${#{change.logical_id}}", arn: arn) }
164
+ end
165
+
166
+ def self.properties_of(change, side)
167
+ value = side == :old ? change.old_value : change.new_value
168
+ value.is_a?(Hash) ? value["Properties"] : nil
169
+ end
170
+
171
+ # The resource definitions of one side, for the capability table.
172
+ def self.diff_resources(diff, side)
173
+ diff.resources.each_value.filter_map do |change|
174
+ value = side == :old ? change.old_value : change.new_value
175
+ value if value.is_a?(Hash)
176
+ end
177
+ end
178
+
179
+ # Multiset difference: what one side carries that the other does not,
180
+ # matched one entry to one entry by what it says.
181
+ def self.added(entries, against)
182
+ unmatched = against.dup
183
+ entries.reject do |entry|
184
+ at = unmatched.find_index { |candidate| candidate.equal?(entry) }
185
+ if at.nil?
186
+ false
187
+ else
188
+ unmatched.delete_at(at)
189
+ true
190
+ end
191
+ end
192
+ end
193
+
194
+ # True when any of the properties is one this view reads.
195
+ def self.watched_property?(properties)
196
+ return false unless properties.is_a?(Hash)
197
+
198
+ walk(properties).any?
199
+ end
200
+
201
+ # The statements one resource's properties carry, exact by resource type.
202
+ def self.read_statements(type, properties, logical_id)
203
+ rendered = RenderIntrinsics.call(properties)
204
+
205
+ return [ Statement.from_lambda_permission(rendered) ] if type == "AWS::Lambda::Permission"
206
+ return identity_policy_resource(rendered, logical_id) if type == "AWS::IAM::Policy"
207
+ return attached_policy_resource(rendered) if ATTACHED_POLICY_TYPES.include?(type)
208
+
209
+ statements = []
210
+ walk(rendered) { |path, value| statements.concat(policy_statements(type, path, value, logical_id)) }
211
+ statements
212
+ end
213
+
214
+ # The walk: every property whose name carries a policy document, at any
215
+ # depth of the resource's properties. This is what makes the view exact:
216
+ # nothing the template carries as a statement can walk past it. Without
217
+ # a block it answers the enumerator of the hits.
218
+ def self.walk(value, path = [], &block)
219
+ return enum_for(:walk, value, path) unless block
220
+
221
+ case value
222
+ when Hash
223
+ value.each do |key, entry|
224
+ here = path + [ key ]
225
+ if POLICY_PROPERTIES.include?(key)
226
+ block.call(here, entry)
227
+ else
228
+ walk(entry, here, &block)
229
+ end
230
+ end
231
+ when Array
232
+ value.each_with_index { |entry, index| walk(entry, path + [ index ], &block) }
233
+ end
234
+ end
235
+
236
+ # The statements of one policy document found at one path, with the
237
+ # defaults the place gives them:
238
+ #
239
+ # - the inline Policies of a Role, User or Group apply to the identity
240
+ # itself: their principal is the resource (the CDK's
241
+ # readIdentityPolicies);
242
+ # - every other policy document applies to the resource that carries it,
243
+ # where the statement does not name one (the CDK's
244
+ # readResourceStatements).
245
+ def self.policy_statements(type, path, value, logical_id)
246
+ document = value.is_a?(Hash) && value["Statement"] ? value : nil
247
+ return [] unless document
248
+
249
+ statements = parse_statements(document["Statement"])
250
+ if IDENTITY_TYPES.include?(type) && path.include?("Policies")
251
+ statements.each { |statement| statement.principals.replace_empty_or_star("AWS:${#{logical_id}}") }
252
+ else
253
+ statements.each { |statement| statement.resources.replace_empty_or_star("${#{logical_id}.Arn}") }
254
+ end
255
+ statements
256
+ end
257
+
258
+ # AWS::IAM::Policy: one statement set per principal the policy attaches
259
+ # to, each "AWS:" plus what the Roles, Users and Groups name (the CDK's
260
+ # readIdentityPolicyResource).
261
+ def self.identity_policy_resource(properties, logical_id)
262
+ principals = Array(properties["Groups"]) + Array(properties["Users"]) + Array(properties["Roles"])
263
+ document = properties["PolicyDocument"]
264
+ return [] unless document.is_a?(Hash)
265
+
266
+ principals.flat_map do |principal|
267
+ statements = parse_statements(document["Statement"])
268
+ statements.each { |statement| statement.principals.replace_empty_or_star("AWS:#{principal}") }
269
+ end
270
+ end
271
+
272
+ # The policies attached to a resource of their own (a bucket policy, a
273
+ # queue policy, a topic policy): the statement's resource is the
274
+ # property that names the resource, the one key that is neither a policy
275
+ # nor a name (the CDK's readResourcePolicyResource).
276
+ def self.attached_policy_resource(properties)
277
+ policy_keys = properties.keys.select { |key| key.include?("Policy") }
278
+ resource_keys = properties.keys.select { |key| !policy_keys.include?(key) && !key.end_with?("Name") }
279
+ resources = resource_keys.length == 1 ? properties[resource_keys.first] : "???"
280
+ policy_key = policy_keys.first
281
+ return [] if policy_key.nil? || !properties[policy_key].is_a?(Hash)
282
+
283
+ Array(resources).flat_map do |resource|
284
+ statements = parse_statements(properties[policy_key]["Statement"])
285
+ statements.each { |statement| statement.resources.replace_empty_or_star(resource) }
286
+ end
287
+ end
288
+
289
+ # parseStatements: one statement or a list of them. A Hash is one
290
+ # statement, never a list of pairs.
291
+ def self.parse_statements(value)
292
+ statements = if value.nil?
293
+ []
294
+ elsif value.is_a?(Array)
295
+ value
296
+ else
297
+ [ value ]
298
+ end
299
+ statements.map { |statement| Statement.new(statement) }
300
+ end
301
+
302
+ # The capabilities a template's resources ask of CloudFormation:
303
+ # CAPABILITY_IAM for any of the eight types, CAPABILITY_NAMED_IAM with it
304
+ # when one of them is named explicitly. The answer deploy computes for
305
+ # the change set, computed here for the view.
306
+ def self.capability_set(resources)
307
+ iam = resources.select { |resource| CAPABILITY_TYPES.include?(resource["Type"]) }
308
+ return [] if iam.empty?
309
+
310
+ named = iam.any? do |resource|
311
+ properties = resource["Properties"]
312
+ properties.is_a?(Hash) && NAME_PROPERTIES.any? { |property| !properties[property].nil? }
313
+ end
314
+ named ? %w[CAPABILITY_IAM CAPABILITY_NAMED_IAM] : %w[CAPABILITY_IAM]
315
+ end
316
+
317
+ private_class_method :change_statements, :managed_policies, :diff_resources, :added,
318
+ :read_statements, :walk, :policy_statements, :identity_policy_resource,
319
+ :attached_policy_resource, :parse_statements, :capability_set
320
+ end
321
+ end
322
+ end
@@ -0,0 +1,256 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module RubyCdk
6
+ module Diff
7
+ # CloudFormation intrinsics written the way a person reads them, the CDK's
8
+ # renderIntrinsics (cloudformation-diff, lib/render-intrinsics.ts at
9
+ # eca1b73d682d7763955bec30ab5dd52bbc4327b6): a Ref becomes ${LogicalId},
10
+ # Fn::GetAtt becomes ${LogicalId.Attribute}, a literal Fn::Join is joined,
11
+ # any other intrinsic is shown as its JSON, and AWS::NoValue disappears.
12
+ # Not meant to parse back into a template; meant to be understood.
13
+ module RenderIntrinsics
14
+ module_function
15
+
16
+ def call(value)
17
+ case value
18
+ when Array
19
+ value.reject { |entry| no_value?(entry) }.map { |entry| call(entry) }
20
+ when Hash
21
+ if (intrinsic = intrinsic_of(value))
22
+ return render_intrinsic(intrinsic)
23
+ end
24
+
25
+ value.each_with_object({}) do |(key, entry), rendered|
26
+ rendered[key] = call(entry) unless no_value?(entry)
27
+ end
28
+ else
29
+ value
30
+ end
31
+ end
32
+
33
+ def render_intrinsic(intrinsic)
34
+ fn, arguments = intrinsic
35
+ case fn
36
+ when "Ref" then "${#{call(arguments)}}"
37
+ when "Fn::GetAtt"
38
+ parts = arguments.is_a?(Array) ? arguments : arguments.to_s.split(".")
39
+ "${#{parts.map { |part| call(part) }.join(".")}}"
40
+ when "Fn::Join"
41
+ separator, items = arguments.is_a?(Array) ? arguments : [ nil, arguments ]
42
+ items.is_a?(Array) ? items.reject { |entry| no_value?(entry) }.map { |entry| call(entry) }.join(separator.to_s) : intrinsic_json(fn, arguments)
43
+ else
44
+ intrinsic_json(fn, arguments)
45
+ end
46
+ end
47
+
48
+ def intrinsic_json(fn, arguments)
49
+ JSON.generate({ fn => call(arguments) })
50
+ end
51
+
52
+ def intrinsic_of(value)
53
+ keys = value.keys
54
+ return nil unless keys.length == 1
55
+
56
+ key = keys.first
57
+ return nil unless key == "Ref" || key.start_with?("Fn::")
58
+
59
+ [ key, value[key] ]
60
+ end
61
+
62
+ def no_value?(value)
63
+ return false unless value.is_a?(Hash)
64
+
65
+ value.keys == [ "Ref" ] && value["Ref"] == "AWS::NoValue"
66
+ end
67
+ end
68
+
69
+ # One IAM policy statement, the CDK's Statement (cloudformation-diff,
70
+ # lib/iam/statement.ts). Two statements are the same when everything they
71
+ # say is the same, which is how the security view tells an added statement
72
+ # from one that was already deployed.
73
+ class Statement
74
+ EFFECTS = %w[Allow Deny].freeze
75
+
76
+ attr_reader :sid, :effect, :condition, :serialized, :resources, :actions, :principals
77
+
78
+ # statement is the Hash of one statement, or a string when the template
79
+ # carries something there that is not a statement Hash (the CDK keeps it
80
+ # as a serialized intrinsic and shows it as it is).
81
+ def initialize(statement)
82
+ if statement.is_a?(String)
83
+ @sid = nil
84
+ @effect = "Unknown"
85
+ @resources = Targets.new({}, nil, nil)
86
+ @actions = Targets.new({}, nil, nil)
87
+ @principals = Targets.new({}, nil, nil)
88
+ @condition = nil
89
+ @serialized = statement
90
+ else
91
+ map = statement || {}
92
+ @sid = map["Sid"].is_a?(String) ? map["Sid"] : nil
93
+ @effect = EFFECTS.include?(map["Effect"]) ? map["Effect"] : "Unknown"
94
+ @resources = Targets.new(map, "Resource", "NotResource")
95
+ @actions = Targets.new(map, "Action", "NotAction")
96
+ @principals = Targets.new(map, "Principal", "NotPrincipal")
97
+ @condition = map["Condition"]
98
+ @serialized = nil
99
+ end
100
+ end
101
+
102
+ # True when the two statements say exactly the same thing.
103
+ def equal?(other)
104
+ sid == other.sid && effect == other.effect && serialized == other.serialized &&
105
+ resources.equal?(other.resources) && actions.equal?(other.actions) &&
106
+ principals.equal?(other.principals) && condition == other.condition
107
+ end
108
+
109
+ # A statement broadens permissions when it grants something: it is a
110
+ # positive Allow or a negative Deny. The CDK's isNegativeStatement.
111
+ def negative?
112
+ not_target = actions.not? || principals.not? || resources.not?
113
+ effect == "Allow" ? not_target : !not_target
114
+ end
115
+
116
+ # The row of the security view's statement table, as the CDK's render:
117
+ # one column each for the resource, the effect, the action, the
118
+ # principal and the condition.
119
+ def render
120
+ return { resource: serialized, effect: "", action: "", principal: principals.render, condition: "" } if serialized
121
+
122
+ {
123
+ resource: resources.render,
124
+ effect: effect,
125
+ action: actions.render,
126
+ principal: principals.render,
127
+ condition: render_condition(condition)
128
+ }
129
+ end
130
+
131
+ # The machine-readable statement (--json), as the CDK's _toJson.
132
+ def to_h
133
+ return { "serialized" => serialized } if serialized
134
+
135
+ {
136
+ "sid" => sid,
137
+ "effect" => effect,
138
+ "resources" => resources.to_h,
139
+ "actions" => actions.to_h,
140
+ "principals" => principals.to_h,
141
+ "condition" => condition
142
+ }.compact
143
+ end
144
+
145
+ # The CDK's parseLambdaPermission: what Lambda::Permission says, written
146
+ # as the statement Lambda adds to the function's policy when the
147
+ # permission is granted.
148
+ def self.from_lambda_permission(properties)
149
+ properties ||= {}
150
+ statement = {
151
+ "Effect" => "Allow",
152
+ "Action" => properties["Action"],
153
+ "Resource" => properties["FunctionName"]
154
+ }
155
+ principal = properties["Principal"]
156
+ unless principal.nil?
157
+ statement["Principal"] = if principal == "*"
158
+ "*"
159
+ elsif principal.match?(/\A\d{12}\z/)
160
+ { "AWS" => "arn:aws:iam::#{principal}:root" }
161
+ else
162
+ { "Service" => principal }
163
+ end
164
+ end
165
+ condition_of(properties, "SourceArn", "ArnLike", "AWS:SourceArn", statement)
166
+ condition_of(properties, "SourceAccount", "StringEquals", "AWS:SourceAccount", statement)
167
+ condition_of(properties, "EventSourceToken", "StringEquals", "lambda:EventSourceToken", statement)
168
+ new(statement)
169
+ end
170
+
171
+ def self.condition_of(properties, property, operator, key, statement)
172
+ return if properties[property].nil?
173
+
174
+ statement["Condition"] ||= {}
175
+ statement["Condition"][operator] = { key => properties[property] }
176
+ end
177
+
178
+ private_class_method :condition_of
179
+
180
+ private
181
+
182
+ # The condition column: the JSON of the condition, without the outermost
183
+ # braces and the indentation, which is how the CDK renders it.
184
+ def render_condition(condition)
185
+ return "" if condition.nil? || (condition.is_a?(Hash) && condition.empty?)
186
+
187
+ lines = JSON.pretty_generate(condition).split("\n")
188
+ inner = lines[1...-1] || []
189
+ inner.map { |line| line.delete_prefix(" ") }.join("\n")
190
+ end
191
+ end
192
+
193
+ # The values of one field of a statement (Resource, Action, Principal),
194
+ # the CDK's Targets: sorted, strings or NOT-strings, joined by newlines
195
+ # when there are several.
196
+ class Targets
197
+ attr_reader :values
198
+
199
+ # statement is the statement Hash, positive_key the field that grants and
200
+ # negative_key the one that excludes (NotAction and friends).
201
+ def initialize(statement, positive_key, negative_key)
202
+ if negative_key && statement.key?(negative_key)
203
+ @values = strings_of(statement[negative_key])
204
+ @not = true
205
+ else
206
+ @values = negative_key ? strings_of(statement[positive_key]) : []
207
+ @not = false
208
+ end
209
+ @values.sort!
210
+ end
211
+
212
+ def not?
213
+ @not
214
+ end
215
+
216
+ # True when the two targets say the same things of the same kind.
217
+ def equal?(other)
218
+ @not == other.not? && values == other.values.sort
219
+ end
220
+
221
+ # The default the place of the statement gives the field: a field left
222
+ # empty, or left as "*", takes it (the CDK's replaceEmpty and
223
+ # replaceStar, which its statement defaults are written with).
224
+ def replace_empty_or_star(value)
225
+ values << value if values.empty?
226
+ values.map! { |entry| entry == "*" ? value : entry }
227
+ values.sort!
228
+ self
229
+ end
230
+
231
+ def render
232
+ @not ? values.map { |value| "NOT #{value}" }.join("\n") : values.join("\n")
233
+ end
234
+
235
+ def to_h
236
+ { "not" => @not, "values" => values }
237
+ end
238
+
239
+ private
240
+
241
+ # The CDK's forceListOfStrings: a string is one value, a list is its
242
+ # elements flattened into strings, an object is its entries as
243
+ # "key:Value", everything else is its string.
244
+ def strings_of(value)
245
+ case value
246
+ when String then [ value ]
247
+ when nil then []
248
+ when Array then value.map { |entry| strings_of(entry).join(",") }
249
+ when Hash
250
+ value.flat_map { |key, entry| strings_of(entry).map { |entry_string| "#{key}:#{entry_string}" } }
251
+ else [ value.to_s ]
252
+ end
253
+ end
254
+ end
255
+ end
256
+ end