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,303 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require_relative "report"
5
+ require_relative "rules"
6
+
7
+ module RubyCdk
8
+ module Nag
9
+ # .ruby-cdk/nag.yml says something that cannot be understood, so nothing
10
+ # is assumed: an unknown key, a threshold that is not one of the three, a
11
+ # rule id that no rule has. A usage error, so exit 1.
12
+ class ConfigError < RubyCdk::UsageError; end
13
+
14
+ # One suppression written in the configuration file.
15
+ #
16
+ # applies_to narrows it to resources whose logical ID or type matches the
17
+ # glob; nil covers every resource.
18
+ Suppression = Data.define(:id, :reason, :applies_to)
19
+
20
+ # What a run of the rules is told: the threshold, what to suppress, which
21
+ # rules run, and which resource types are stateful.
22
+ #
23
+ # The file, at the root of a project:
24
+ #
25
+ # threshold: medium # high, medium or low; the default
26
+ # paths_to_suppress: # globs on a stack name or path
27
+ # - "*-sandbox"
28
+ # suppressions: # a suppression without a reason is ignored, with a warning
29
+ # - id: RC-EC2-001
30
+ # reason: The bastion is replaced by SSM Session Manager this quarter.
31
+ # applies_to: "BastionSecurityGroup*" # optional: a glob on the logical ID or the type
32
+ # rules: # false turns a rule off for the whole project
33
+ # RC-LOGS-001: false
34
+ # stateful_types: # optional: what RC-STATE-001 reads; the default is the list below
35
+ # - AWS::S3::Bucket
36
+ #
37
+ # A malformed file is refused with ConfigError. A file that is absent, or
38
+ # empty, is the default configuration.
39
+ #
40
+ # The shape follows cdk-nag (cdklabs/cdk-nag, commit
41
+ # da5bed77c1b08e584e3de2d67534c76871af957f, Apache-2.0), src/nag-pack.ts
42
+ # and README.md "Acknowledging a Rule": a rule is acknowledged with an id
43
+ # and a reason, on one resource or on a whole scope, and one
44
+ # acknowledgement can cover every finding of a rule.
45
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
46
+ # SPDX-License-Identifier: Apache-2.0
47
+ #
48
+ # What changed: cdk-nag has no project file; a pack is configured in
49
+ # code, and its paths are regular expressions where the wave card asks
50
+ # for globs. A finding is addressed by its resource here, with applies_to,
51
+ # where cdk-nag addresses it with "RuleId[FindingId]". A suppression
52
+ # without a reason is ignored with a warning, as the wave card decides.
53
+ class Config
54
+ # The file, under the root of a project.
55
+ FILE = ".ruby-cdk/nag.yml"
56
+
57
+ # --fail-on defaults to medium.
58
+ DEFAULT_THRESHOLD = :medium
59
+
60
+ # The resource types the CDK retains or snapshots by default, which are
61
+ # retained here too: the list of architecture section 7 (D-007), the same
62
+ # one synthesis applies. RC-STATE-001 reads it when the configuration
63
+ # names none.
64
+ DEFAULT_STATEFUL_TYPES = %w[
65
+ AWS::S3::Bucket
66
+ AWS::DynamoDB::Table
67
+ AWS::Logs::LogGroup
68
+ AWS::KMS::Key
69
+ AWS::EC2::Volume
70
+ AWS::ECR::Repository
71
+ AWS::Cognito::UserPool
72
+ AWS::Kinesis::Stream
73
+ AWS::OpenSearchService::Domain
74
+ AWS::RDS::DBInstance
75
+ AWS::RDS::DBCluster
76
+ ].freeze
77
+
78
+ KEYS = %i[threshold paths_to_suppress suppressions rules stateful_types].freeze
79
+ SUPPRESSION_KEYS = %i[id reason applies_to].freeze
80
+ RESOURCE_TYPE = /\AAWS::[A-Za-z0-9]+::[A-Za-z0-9]+\z/
81
+
82
+ attr_reader :path, :threshold, :paths_to_suppress, :suppressions, :rules, :stateful_types, :warnings
83
+
84
+ # warnings: Array<Warning>, what the file said and was ignored.
85
+ def initialize(path: nil, threshold: DEFAULT_THRESHOLD, paths_to_suppress: [], suppressions: [], rules: {}, stateful_types: DEFAULT_STATEFUL_TYPES, warnings: [])
86
+ @path = path
87
+ @threshold = threshold
88
+ @paths_to_suppress = paths_to_suppress.freeze
89
+ @suppressions = suppressions.freeze
90
+ @rules = rules.freeze
91
+ @stateful_types = stateful_types.freeze
92
+ @warnings = warnings.freeze
93
+ freeze
94
+ end
95
+
96
+ class << self
97
+ # Nothing suppressed, every rule on, the default threshold.
98
+ def default
99
+ @default ||= new
100
+ end
101
+
102
+ # The configuration of the project whose root is root: its
103
+ # .ruby-cdk/nag.yml, or the default when there is none.
104
+ def load(root = ".")
105
+ from_file(File.expand_path(FILE, root))
106
+ end
107
+
108
+ # The configuration in the file at path, or the default when the file
109
+ # does not exist. A path that exists and cannot be read as a file is
110
+ # refused: it says someone meant a configuration to be there.
111
+ def from_file(path)
112
+ return default unless File.exist?(path)
113
+ raise ConfigError, "#{path} cannot be read: it is not a file" unless File.file?(path)
114
+
115
+ from_hash(parse(File.read(path), path), path)
116
+ rescue SystemCallError => e
117
+ raise ConfigError, "#{path} cannot be read: #{e.message}"
118
+ end
119
+
120
+ # A Config, as it is. A Hash written like the file, with String or
121
+ # Symbol keys, as a Config. nil, the default.
122
+ def coerce(config)
123
+ return config if config.is_a?(Config)
124
+ return default if config.nil?
125
+ raise ArgumentError, "config must be a Nag::Config or a Hash, not a #{config.class}" unless config.is_a?(Hash)
126
+
127
+ from_hash(config, nil)
128
+ end
129
+
130
+ # The configuration a Hash holds. path names where it came from, for
131
+ # the messages. Raises ConfigError when it cannot be understood.
132
+ def from_hash(hash, path)
133
+ where = path || "the configuration"
134
+ unless hash.is_a?(Hash)
135
+ raise ConfigError, "#{where} must hold the keys #{KEYS.map(&:inspect).join(", ")}, and holds #{hash.class}"
136
+ end
137
+
138
+ given = {}
139
+ unknown = []
140
+ hash.each do |key, value|
141
+ if KEYS.include?(key_name(key))
142
+ given[key_name(key)] = value
143
+ else
144
+ unknown << key
145
+ end
146
+ end
147
+ unless unknown.empty?
148
+ raise ConfigError, "#{where} has unknown #{unknown.one? ? "key" : "keys"} #{unknown.map(&:inspect).join(", ")}: the keys are #{KEYS.map(&:inspect).join(", ")}"
149
+ end
150
+
151
+ suppressions, warnings = suppressions_of(given[:suppressions], where)
152
+ new(
153
+ path: path,
154
+ threshold: threshold_of(given[:threshold], where),
155
+ paths_to_suppress: globs_of(given[:paths_to_suppress], "#{where}: paths_to_suppress", "a stack name or path"),
156
+ suppressions: suppressions,
157
+ rules: rules_of(given[:rules], where),
158
+ stateful_types: stateful_types_of(given[:stateful_types], where),
159
+ warnings: warnings
160
+ )
161
+ end
162
+
163
+ private
164
+
165
+ # The key as a Symbol, or nil when it is neither a String nor a Symbol.
166
+ def key_name(key)
167
+ (key.is_a?(String) || key.is_a?(Symbol)) ? key.to_sym : nil
168
+ end
169
+
170
+ def parse(text, path)
171
+ YAML.safe_load(text, permitted_classes: [], permitted_symbols: [], aliases: false, filename: path) || {}
172
+ rescue Psych::SyntaxError => e
173
+ raise ConfigError, "#{path} is not valid YAML: #{e.message}"
174
+ rescue Psych::DisallowedClass, Psych::Exception, ArgumentError => e
175
+ raise ConfigError, "#{path} holds what the file cannot: #{e.message}"
176
+ end
177
+
178
+ def threshold_of(value, where)
179
+ return DEFAULT_THRESHOLD if value.nil?
180
+
181
+ name = key_name(value)
182
+ name = name.to_s.downcase.to_sym if name
183
+ unless SEVERITIES.include?(name)
184
+ raise ConfigError, "#{where}: threshold #{value.inspect} is not one of #{SEVERITIES.map(&:inspect).join(", ")}"
185
+ end
186
+ name
187
+ end
188
+
189
+ # A list of globs, or [] when nothing is given.
190
+ def globs_of(value, where, on)
191
+ return [] if value.nil?
192
+ unless value.is_a?(Array) && value.all? { |glob| glob.is_a?(String) && !glob.strip.empty? }
193
+ raise ConfigError, "#{where} must be a list of globs on #{on}, such as [\"*-sandbox\"]"
194
+ end
195
+
196
+ value.each { |glob| check_glob(glob, where) }
197
+ value
198
+ end
199
+
200
+ def check_glob(glob, where)
201
+ File.fnmatch?(glob, "", File::FNM_EXTGLOB)
202
+ rescue ArgumentError
203
+ raise ConfigError, "#{where} holds #{glob.inspect}, which is not a glob"
204
+ end
205
+
206
+ # [Array<Suppression>, Array<Warning>]. An entry without a reason is
207
+ # not a suppression: it is a warning.
208
+ def suppressions_of(value, where)
209
+ return [ [], [] ] if value.nil?
210
+ unless value.is_a?(Array) && value.all?(Hash)
211
+ raise ConfigError, "#{where}: suppressions must be a list of entries with id, reason and applies_to"
212
+ end
213
+
214
+ suppressions = []
215
+ warnings = []
216
+ value.each_with_index do |entry, index|
217
+ at = "#{where}: suppressions[#{index}]"
218
+ unknown = entry.keys.reject { |key| SUPPRESSION_KEYS.include?(key_name(key)) }
219
+ unless unknown.empty?
220
+ raise ConfigError, "#{at} has unknown #{unknown.one? ? "key" : "keys"} #{unknown.map(&:inspect).join(", ")}: the keys are #{SUPPRESSION_KEYS.map(&:inspect).join(", ")}"
221
+ end
222
+
223
+ id = value_of(entry, :id)
224
+ unless id.is_a?(String) && Rules.ids.include?(id)
225
+ raise ConfigError, "#{at} names #{id.inspect}, and no rule has that id: the ids are #{Rules.ids.join(", ")}"
226
+ end
227
+
228
+ reason = value_of(entry, :reason)
229
+ unless reason.is_a?(String) && !reason.strip.empty?
230
+ warnings << Warning.new(location: at, message: "suppresses #{id} without a reason, and is ignored: a suppression says why it is safe")
231
+ next
232
+ end
233
+
234
+ applies_to = value_of(entry, :applies_to)
235
+ unless applies_to.nil?
236
+ raise ConfigError, "#{at}: applies_to must be a glob on a logical ID or a resource type" unless applies_to.is_a?(String) && !applies_to.strip.empty?
237
+
238
+ check_glob(applies_to, at)
239
+ end
240
+ suppressions << Suppression.new(id: id, reason: reason.strip, applies_to: applies_to)
241
+ end
242
+ [ suppressions, warnings ]
243
+ end
244
+
245
+ def rules_of(value, where)
246
+ return {} if value.nil?
247
+ unless value.is_a?(Hash)
248
+ raise ConfigError, "#{where}: rules must map a rule id to true or false"
249
+ end
250
+
251
+ value.to_h do |id, enabled|
252
+ name = key_name(id)&.to_s
253
+ unless Rules.ids.include?(name)
254
+ raise ConfigError, "#{where}: rules names #{id.inspect}, and no rule has that id: the ids are #{Rules.ids.join(", ")}"
255
+ end
256
+ unless enabled == true || enabled == false
257
+ raise ConfigError, "#{where}: rules has #{name} = #{enabled.inspect}, which is not true or false"
258
+ end
259
+ [ name, enabled ]
260
+ end
261
+ end
262
+
263
+ def stateful_types_of(value, where)
264
+ return DEFAULT_STATEFUL_TYPES if value.nil?
265
+ unless value.is_a?(Array) && value.all? { |type| type.is_a?(String) && RESOURCE_TYPE.match?(type) }
266
+ raise ConfigError, "#{where}: stateful_types must be a list of resource types, such as [\"AWS::S3::Bucket\"]"
267
+ end
268
+ value
269
+ end
270
+
271
+ # The value under the key, whether it is written id or :id.
272
+ def value_of(entry, key)
273
+ entry.fetch(key) { entry[key.to_s] }
274
+ end
275
+ end
276
+
277
+ # True when the rule runs in this project.
278
+ def rule_enabled?(id)
279
+ @rules.fetch(id, true)
280
+ end
281
+
282
+ # The first glob of paths_to_suppress that matches one of the stack's
283
+ # locations (its name and its path), or nil when none does.
284
+ def suppressed_path(locations)
285
+ @paths_to_suppress.find do |glob|
286
+ locations.compact.any? { |location| File.fnmatch?(glob, location.to_s, File::FNM_EXTGLOB) }
287
+ end
288
+ end
289
+
290
+ # The suppression written for this rule that covers the resource, or
291
+ # nil. A suppression with applies_to covers the resource when the glob
292
+ # matches its logical ID or its type.
293
+ def suppression_for(id, logical_id, resource_type)
294
+ @suppressions.find do |suppression|
295
+ next false unless suppression.id == id
296
+ next true if suppression.applies_to.nil?
297
+
298
+ [ logical_id, resource_type ].compact.any? { |name| File.fnmatch?(suppression.applies_to, name.to_s, File::FNM_EXTGLOB) }
299
+ end
300
+ end
301
+ end
302
+ end
303
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "config"
4
+ require_relative "rule"
5
+
6
+ module RubyCdk
7
+ module Nag
8
+ # Runs the rule pack over a template, a plain Hash in CloudFormation
9
+ # syntax, and applies the suppressions.
10
+ #
11
+ # Ported from cdk-nag (cdklabs/cdk-nag, commit
12
+ # da5bed77c1b08e584e3de2d67534c76871af957f, Apache-2.0), src/nag-pack.ts:
13
+ # every rule runs on every resource; a finding is dropped when the rule is
14
+ # acknowledged; a rule that cannot read a value is neither passed nor
15
+ # forgotten; and an acknowledgement is written into the resource's
16
+ # CloudFormation Metadata by WriteNagSuppressionsToCloudFormationAspect,
17
+ # as cdk_nag: { rules_to_suppress: [{ id, reason }] }.
18
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
19
+ # SPDX-License-Identifier: Apache-2.0
20
+ #
21
+ # What changed: a value that is an intrinsic makes the check a Skipped
22
+ # record, counted as not evaluated, where the source reports the rule as
23
+ # failed with "Rule threw an error during validation". The key of the
24
+ # suppression is "RubyCdk::Nag" and its list "RulesToSuppress", as the
25
+ # wave card names them. Acknowledgements are read on the resource alone: a
26
+ # template has no construct tree to walk up, so a whole scope cannot be
27
+ # acknowledged in it. An acknowledgement without a reason is ignored, with
28
+ # a warning, where the source keeps it. A finding is acknowledged by its
29
+ # rule on the resource, or by a suppression of the configuration file whose
30
+ # applies_to matches the resource; "RuleId[FindingId]" is not ported.
31
+ class Engine
32
+ RESOURCES = "Resources"
33
+ METADATA = "Metadata"
34
+ SUPPRESSIONS = "RubyCdk::Nag"
35
+ RULES_TO_SUPPRESS = "RulesToSuppress"
36
+ ID = "Id"
37
+ REASON = "Reason"
38
+ SUPPRESSION_KEYS = [ ID, REASON ].freeze
39
+
40
+ attr_reader :rules
41
+
42
+ # rules: the rule classes to run. Raises DefinitionError when one of them
43
+ # is malformed, or when two share an id: that is a fault in this gem.
44
+ def initialize(rules: Rules::ALL)
45
+ @rules = rules
46
+ @rules.each do |rule|
47
+ problems = rule.definition_problems
48
+ raise DefinitionError, "#{rule}: #{problems.join("; ")}" unless problems.empty?
49
+ end
50
+
51
+ shared = @rules.map(&:id).tally.select { |_, count| count > 1 }.keys
52
+ raise DefinitionError, "several rules share an id: #{shared.join(", ")}" unless shared.empty?
53
+ end
54
+
55
+ # One template, one Report.
56
+ #
57
+ # config: a Config, or a Hash written like nag.yml; nil is the default.
58
+ # locations: where the stack is, its name and its path, which the globs
59
+ # of paths_to_suppress are matched against.
60
+ def check(template, config: nil, locations: [])
61
+ config = Config.coerce(config)
62
+ violations = []
63
+ skipped = []
64
+ suppressed = []
65
+ # What the configuration said and was ignored is part of what this run found.
66
+ warnings = config.warnings.dup
67
+ path_glob = config.suppressed_path(locations)
68
+
69
+ resources_in(template).each do |logical_id, resource|
70
+ acknowledgements = suppressions_in(resource, logical_id, warnings)
71
+
72
+ @rules.each do |rule_class|
73
+ next unless config.rule_enabled?(rule_class.id)
74
+
75
+ rule = rule_class.new(resource, logical_id: logical_id, config: config)
76
+ next unless rule.applicable?
77
+
78
+ outcome = rule.run
79
+ skipped.concat(outcome.skipped)
80
+ outcome.violations.each do |violation|
81
+ suppression = acknowledgements[violation.rule] || config.suppression_for(violation.rule, logical_id, violation.resource_type)
82
+ reason = if suppression
83
+ suppression.reason
84
+ elsif path_glob
85
+ "the stack matches paths_to_suppress #{path_glob.inspect} in #{Config::FILE}"
86
+ end
87
+
88
+ if reason
89
+ suppressed << Suppressed.new(rule: violation.rule, severity: violation.severity, logical_id: violation.logical_id,
90
+ resource_type: violation.resource_type, path: violation.path, message: violation.message, reason: reason)
91
+ else
92
+ violations << violation
93
+ end
94
+ end
95
+ end
96
+ end
97
+
98
+ Report.new(violations: violations, skipped: skipped, suppressed: suppressed, warnings: warnings)
99
+ end
100
+
101
+ private
102
+
103
+ # Every resource of the template that is a mapping, in the order written.
104
+ def resources_in(template)
105
+ return [] unless template.is_a?(Hash)
106
+
107
+ resources = template[RESOURCES]
108
+ return [] unless resources.is_a?(Hash)
109
+
110
+ resources.select { |_logical_id, resource| resource.is_a?(Hash) }
111
+ end
112
+
113
+ # The acknowledgements written in the resource's Metadata: { rule id =>
114
+ # Suppression }. One that is not shaped right, that names no rule, or
115
+ # that has no reason is ignored, and a Warning says so.
116
+ def suppressions_in(resource, logical_id, warnings)
117
+ metadata = resource[METADATA]
118
+ return {} unless metadata.is_a?(Hash)
119
+
120
+ entries = metadata[SUPPRESSIONS]
121
+ return {} unless entries.is_a?(Hash)
122
+
123
+ list = entries[RULES_TO_SUPPRESS]
124
+ return {} unless list.is_a?(Array)
125
+
126
+ found = {}
127
+ list.each_with_index do |entry, index|
128
+ at = "Resources/#{logical_id}/#{METADATA}/#{SUPPRESSIONS}/#{RULES_TO_SUPPRESS}[#{index}]"
129
+ unless entry.is_a?(Hash) && entry.keys.all? { |key| SUPPRESSION_KEYS.include?(key) }
130
+ warnings << Warning.new(location: at, message: "is not written as {\"Id\" => <rule>, \"Reason\" => <why>}, and is ignored")
131
+ next
132
+ end
133
+
134
+ id = entry[ID]
135
+ unless id.is_a?(String) && Rules.ids.include?(id)
136
+ warnings << Warning.new(location: at, message: "names #{id.inspect}, and no rule has that id; it is ignored")
137
+ next
138
+ end
139
+
140
+ reason = entry[REASON]
141
+ unless reason.is_a?(String) && !reason.strip.empty?
142
+ warnings << Warning.new(location: at, message: "suppresses #{id} without a reason, and is ignored: a suppression says why it is safe")
143
+ next
144
+ end
145
+
146
+ found[id] ||= Suppression.new(id: id, reason: reason.strip, applies_to: nil)
147
+ end
148
+ found
149
+ end
150
+ end
151
+ end
152
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Nag
5
+ # The severities a rule can have, from the most to the least serious.
6
+ SEVERITIES = %i[high medium low].freeze
7
+
8
+ # How serious each severity is. A threshold fails a violation of the same rank or higher.
9
+ SEVERITY_RANK = { high: 3, medium: 2, low: 1 }.freeze
10
+
11
+ # One finding of one rule on one resource.
12
+ #
13
+ # path locates the finding inside the resource, as the keys are written in the
14
+ # template: "Properties.Encrypted", "Properties.SecurityGroupIngress[1].CidrIp",
15
+ # "DeletionPolicy".
16
+ Violation = Data.define(:rule, :severity, :logical_id, :resource_type, :path, :message)
17
+
18
+ # A check a rule could not finish. reason says what stood in the way, for
19
+ # example "Properties.Encrypted is {\"Ref\"=>\"Encrypted\"}, a dynamic value".
20
+ # A skipped check is neither a pass nor a failure: it is reported as not evaluated.
21
+ Skipped = Data.define(:rule, :logical_id, :resource_type, :path, :reason)
22
+
23
+ # A violation that a suppression covered. The finding is kept, with the
24
+ # reason of the suppression, so that a report shows what was hidden.
25
+ Suppressed = Data.define(:rule, :severity, :logical_id, :resource_type, :path, :message, :reason)
26
+
27
+ # Something that was ignored instead of acted upon, such as a suppression
28
+ # without a reason. location names the file or the resource it was found in.
29
+ Warning = Data.define(:location, :message)
30
+
31
+ # What one template's check found: every violation, every check that could
32
+ # not be decided, every finding a suppression covered, and every warning.
33
+ class Report
34
+ attr_reader :violations, :skipped, :suppressed, :warnings
35
+
36
+ # violations: Array<Violation>. skipped: Array<Skipped>. suppressed: Array<Suppressed>. warnings: Array<Warning>.
37
+ # Each list is copied and frozen: the report is made once, and the lists
38
+ # the caller handed in stay its own.
39
+ def initialize(violations: [], skipped: [], suppressed: [], warnings: [])
40
+ @violations = violations.dup.freeze
41
+ @skipped = skipped.dup.freeze
42
+ @suppressed = suppressed.dup.freeze
43
+ @warnings = warnings.dup.freeze
44
+ end
45
+
46
+ # True when a violation is at threshold or above: fails?(:medium) is true
47
+ # for a medium or a high violation, and false when only low ones were found.
48
+ # threshold is :high, :medium or :low.
49
+ def fails?(threshold)
50
+ rank = SEVERITY_RANK.fetch(threshold) { raise ArgumentError, "threshold must be one of #{SEVERITIES.inspect}, got #{threshold.inspect}" }
51
+ @violations.any? { |violation| SEVERITY_RANK.fetch(violation.severity) >= rank }
52
+ end
53
+
54
+ # The severity of the most serious violation, or nil when there is none.
55
+ def worst_severity
56
+ @violations.map { |violation| SEVERITY_RANK.fetch(violation.severity) }.max&.then { |rank| SEVERITY_RANK.key(rank) }
57
+ end
58
+
59
+ # The violations of each rule: { rule id => Array<Violation> }, in rule order.
60
+ def by_rule
61
+ @violations.group_by(&:rule)
62
+ end
63
+
64
+ # The number of checks that could not be decided.
65
+ def skipped_count
66
+ @skipped.length
67
+ end
68
+
69
+ # True when nothing was found at all: no violation, nothing suppressed, nothing skipped, no warning.
70
+ def empty?
71
+ @violations.empty? && @skipped.empty? && @suppressed.empty? && @warnings.empty?
72
+ end
73
+
74
+ # One report that holds everything these reports hold, in the order given.
75
+ def self.merge(reports)
76
+ reports = reports.to_a
77
+ Report.new(
78
+ violations: reports.flat_map(&:violations),
79
+ skipped: reports.flat_map(&:skipped),
80
+ suppressed: reports.flat_map(&:suppressed),
81
+ warnings: reports.flat_map(&:warnings)
82
+ )
83
+ end
84
+ end
85
+ end
86
+ end