Class: Chef::Compliance::Runner

Inherits:
EventDispatch::Base show all
Extended by:
Forwardable
Defined in:
lib/chef/compliance/runner.rb

Constant Summary collapse

SUPPORTED_REPORTERS =
%w{chef-automate chef-server-automate json-file audit-enforcer compliance-enforcer cli}.freeze
SUPPORTED_FETCHERS =
%w{chef-automate chef-server}.freeze
DEPRECATED_CONFIG_VALUES =

Below code adapted from audit cookbook’s files/default/handler/audit_report.rb

%w{
  attributes_save
  fail_if_not_present
  inspec_gem_source
  inspec_version
  owner
  raise_if_unreachable
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from EventDispatch::Base

#action_collection_registration, #attribute_changed, #attribute_file_load_failed, #attribute_file_loaded, #attribute_load_complete, #attribute_load_start, #compliance_input_enabled, #compliance_input_loaded, #compliance_load_complete, #compliance_load_start, #compliance_profile_enabled, #compliance_profile_loaded, #compliance_waiver_enabled, #compliance_waiver_loaded, #converge_complete, #converge_failed, #cookbook_clean_complete, #cookbook_clean_start, #cookbook_compilation_complete, #cookbook_gem_failed, #cookbook_gem_finished, #cookbook_gem_installing, #cookbook_gem_start, #cookbook_gem_using, #cookbook_resolution_complete, #cookbook_resolution_failed, #cookbook_resolution_start, #cookbook_sync_complete, #cookbook_sync_failed, #cookbook_sync_start, #definition_file_load_failed, #definition_file_loaded, #definition_load_complete, #definition_load_start, #deprecation, #handler_executed, #handlers_completed, #handlers_start, #inputs_load_complete, #inputs_load_start, #key_migration_status, #library_file_load_failed, #library_file_loaded, #library_load_complete, #library_load_start, #lwrp_file_load_failed, #lwrp_file_loaded, #lwrp_load_complete, #lwrp_load_start, #msg, #node_load_failed, #node_load_start, #node_load_success, #ohai_completed, #ohai_plugin_file_load_failed, #ohai_plugin_file_loaded, #ohai_plugin_load_complete, #ohai_plugin_load_start, #policyfile_loaded, #profiles_load_complete, #profiles_load_start, #provider_requirement_failed, #recipe_file_load_failed, #recipe_file_loaded, #recipe_load_complete, #recipe_load_start, #recipe_not_found, #registration_completed, #registration_failed, #registration_start, #removed_cookbook_file, #resource_action_start, #resource_after_state_loaded, #resource_bypassed, #resource_completed, #resource_current_state_load_bypassed, #resource_current_state_loaded, #resource_failed, #resource_failed_retriable, #resource_skipped, #resource_up_to_date, #resource_update_applied, #resource_update_progress, #resource_updated, #run_list_expand_failed, #run_list_expanded, #run_start, #skipping_registration, #stream_closed, #stream_opened, #stream_output, #synchronized_cookbook, #updated_cookbook_file, #waivers_load_complete, #waivers_load_start, #whyrun_assumption

Instance Attribute Details

#nodeObject

Returns the value of attribute node.



14
15
16
# File 'lib/chef/compliance/runner.rb', line 14

def node
  @node
end

#run_contextObject (readonly)

Returns the value of attribute run_context.



15
16
17
# File 'lib/chef/compliance/runner.rb', line 15

def run_context
  @run_context
end

#run_idObject

Returns the value of attribute run_id.



13
14
15
# File 'lib/chef/compliance/runner.rb', line 13

def run_id
  @run_id
end

Instance Method Details

#chef_server_automate_urlObject



312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/chef/compliance/runner.rb', line 312

def chef_server_automate_url
  url = if node["audit"]["server"]
          URI(node["audit"]["server"])
        else
          URI(Chef::Config[:chef_server_url]).tap do |u|
            u.path = ""
          end
        end

  org = Chef::Config[:chef_server_url].split("/").last
  url.path = File.join(url.path, "organizations/#{org}/data-collector")
  url
end

#converge_start(run_context) ⇒ Object



60
61
62
63
64
65
66
67
# File 'lib/chef/compliance/runner.rb', line 60

def converge_start(run_context)
  # With all attributes - including cookbook - loaded, we now have enough data to validate
  # configuration.  Because the converge is best coupled with the associated compliance run, these validations
  # will raise (and abort the converge) if the compliance phase configuration is incorrect/will
  # prevent compliance phase from completing and submitting its report to all configured reporters.
  # can abort the converge if the compliance phase configuration (node attributes and client config)
  load_and_validate!
end

#cookbook_compilation_start(run_context) ⇒ Object

This hook gives us the run_context immediately after it is created so that we can wire up this object to it.

(see EventDispatch::Base#)



52
53
54
# File 'lib/chef/compliance/runner.rb', line 52

def cookbook_compilation_start(run_context)
  @run_context = run_context
end

#create_timestamp_fileObject



374
375
376
# File 'lib/chef/compliance/runner.rb', line 374

def create_timestamp_file
  FileUtils.touch report_timing_file
end

#enabled?Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/chef/compliance/runner.rb', line 19

def enabled?
  return false if @node.nil?

  # Did we parse the libraries file from the audit cookbook?  This class dates back to when Chef Automate was
  # renamed from Chef Visibility in 2017, so should capture all modern versions of the audit cookbook.
  audit_cookbook_present = defined?(::Reporter::ChefAutomate)

  logger.debug("#{self.class}##{__method__}: #{Inspec::Dist::PRODUCT_NAME} profiles? #{inspec_profiles.any?}")
  logger.debug("#{self.class}##{__method__}: audit cookbook? #{audit_cookbook_present}")
  logger.debug("#{self.class}##{__method__}: compliance phase attr? #{node["audit"]["compliance_phase"]}")

  if safe_profile_collection&.using_profiles?
    true
  elsif node["audit"]["compliance_phase"].nil?
    inspec_profiles.any? && !audit_cookbook_present
  else
    node["audit"]["compliance_phase"]
  end
end

#failed_report(err) ⇒ Object

In case InSpec raises a runtime exception without providing a valid report, we make one up and add two new fields to it: ‘status` and `status_message`



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/chef/compliance/runner.rb', line 231

def failed_report(err)
  logger.error "#{Inspec::Dist::PRODUCT_NAME} has raised a runtime exception. Generating a minimal failed report."
  logger.error err
  {
    "platform": {
      "name": "unknown",
      "release": "unknown",
    },
    "profiles": [],
    "statistics": {
      "duration": 0.0000001,
    },
    "version": Inspec::VERSION,
    "status": "failed",
    "status_message": err,
  }
end

#generate_report(opts: inspec_opts, profiles: inspec_profiles) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/chef/compliance/runner.rb', line 205

def generate_report(opts: inspec_opts, profiles: inspec_profiles)
  load_fetchers!

  logger.debug "Options are set to: #{opts}"
  runner = ::Inspec::Runner.new(opts)

  if profiles.empty?
    failed_report("No #{Inspec::Dist::PRODUCT_NAME} profiles are defined.")
    return
  end

  profiles.each { |target| runner.add_target(target) }

  logger.info "Running profiles from: #{profiles.inspect}"
  runner.run
  runner.report.tap do |r|
    logger.debug "Compliance Phase report #{r}"
  end
rescue Inspec::FetcherFailure => e
  failed_report("Cannot fetch all profiles: #{profiles}. Please make sure you're authenticated and the server is reachable. #{e.message}")
rescue => e
  failed_report(e.message)
end

#inputs_from_attributesObject



136
137
138
139
140
141
142
# File 'lib/chef/compliance/runner.rb', line 136

def inputs_from_attributes
  if !node["audit"]["inputs"].empty?
    node["audit"]["inputs"].to_h
  else
    node["audit"]["attributes"].to_h
  end
end

#inputs_from_collectionObject



144
145
146
# File 'lib/chef/compliance/runner.rb', line 144

def inputs_from_collection
  safe_input_collection&.inspec_data || {}
end

#inspec_optsObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/chef/compliance/runner.rb', line 152

def inspec_opts
  inputs = inputs_from_attributes.merge(inputs_from_collection).merge(waivers_from_collection)

  if node["audit"]["chef_node_attribute_enabled"]
    inputs["chef_node"] = node.to_h
    inputs["chef_node"]["chef_environment"] = node.chef_environment
  end

  {
    backend_cache: node["audit"]["inspec_backend_cache"],
    inputs: inputs,
    logger: logger,
    # output: STDOUT,
    output: node["audit"]["quiet"] ? ::File::NULL : STDOUT,
    report: true,
    reporter: ["json-automate"],
    # reporter: ["cli"],
    reporter_backtrace_inclusion: node["audit"]["result_include_backtrace"],
    reporter_message_truncation: node["audit"]["result_message_limit"],
    waiver_file: waiver_files,
  }
end

#inspec_profilesObject



179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/chef/compliance/runner.rb', line 179

def inspec_profiles
  profiles = node["audit"]["profiles"]
  unless profiles.respond_to?(:map) && profiles.all? { |_, p| p.respond_to?(:transform_keys) && p.respond_to?(:update) }
    raise "CMPL010: #{Inspec::Dist::PRODUCT_NAME} profiles specified in an unrecognized format, expected a hash of hashes."
  end

  from_attributes = profiles.map do |name, profile|
    profile.transform_keys(&:to_sym).update(name: name)
  end || []

  from_cookbooks = safe_profile_collection&.inspec_data || []

  from_attributes + from_cookbooks
end

#interval_enabledObject



386
387
388
# File 'lib/chef/compliance/runner.rb', line 386

def interval_enabled
  @interval_enabled ||= node.read("audit", "interval", "enabled")
end

#interval_secondsObject



390
391
392
393
394
395
396
397
398
399
# File 'lib/chef/compliance/runner.rb', line 390

def interval_seconds
  @interval_seconds ||=
    if interval_enabled
      logger.debug "Running Chef Infra Compliance Phase every #{interval_time} minutes"
      interval_time * 60
    else
      logger.debug "Running Chef Infra Compliance Phase on every run"
      0
    end
end

#interval_seconds_leftObject



401
402
403
404
405
406
# File 'lib/chef/compliance/runner.rb', line 401

def interval_seconds_left
  return 0 unless ::File.exist?(report_timing_file)

  seconds_since_last_run = Time.now - ::File.mtime(report_timing_file)
  interval_seconds - seconds_since_last_run
end

#interval_timeObject



382
383
384
# File 'lib/chef/compliance/runner.rb', line 382

def interval_time
  @interval_time ||= node.read("audit", "interval", "time")
end

#load_and_validate!Object

Load the resources required for this runner, and validate configuration is correct to proceed. Requires node state to be loaded. Will raise exception if fetcher is not valid, if a reporter is not valid, or the configuration required by a reporter is not provided.



330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/chef/compliance/runner.rb', line 330

def load_and_validate!
  return unless enabled?

  @reporters = {}
  # Note that the docs don't say you can use an array, but our implementation
  # supports it.
  requested_reporters.each do |type|
    unless SUPPORTED_REPORTERS.include? type
      raise "CMPL003: '#{type}' found in node['audit']['reporter'] is not a supported reporter for Compliance Phase. Supported reporters are: #{SUPPORTED_REPORTERS.join(", ")}. For more information, see the documentation at https://docs.chef.io/chef_compliance_phase#reporters"
    end

    @reporters[type] = reporter(type)
    @reporters[type].validate_config!
  end

  unless (fetcher = node["audit"]["fetcher"]).nil?
    unless SUPPORTED_FETCHERS.include? fetcher
      raise "CMPL002: Unrecognized Compliance Phase fetcher (node['audit']['fetcher'] = #{fetcher}). Supported fetchers are: #{SUPPORTED_FETCHERS.join(", ")}, or nil. For more information, see the documentation at https://docs.chef.io/chef_compliance_phase#fetch-profiles"
    end
  end

  if !node["audit"]["attributes"].empty? && !node["audit"]["inputs"].empty?
    raise "CMPL011: both node['audit']['inputs'] and node['audit']['attributes'] are set.  The node['audit']['attributes'] setting is deprecated and should not be used."
  end

  @validation_passed = true
end

#load_fetchers!Object



194
195
196
197
198
199
200
201
202
203
# File 'lib/chef/compliance/runner.rb', line 194

def load_fetchers!
  case node["audit"]["fetcher"]
  when "chef-automate"
    require_relative "fetcher/automate"
  when "chef-server"
    require_relative "fetcher/chef_server"
  when nil
    # intentionally blank
  end
end

#node_infoObject

extracts relevant node data



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/chef/compliance/runner.rb', line 250

def node_info
  chef_server_uri = URI(Chef::Config[:chef_server_url])

  runlist_roles = node.run_list.select { |item| item.type == :role }.map(&:name)
  runlist_recipes = node.run_list.select { |item| item.type == :recipe }.map(&:name)
  {
    node: node.name,
    os: {
      release: node["platform_version"],
      family: node["platform"],
    },
    environment: node.environment,
    roles: runlist_roles,
    recipes: runlist_recipes,
    policy_name: node.policy_name || "",
    policy_group: node.policy_group || "",
    chef_tags: node.tags,
    organization_name: chef_server_uri.path.split("/").last || "",
    source_fqdn: chef_server_uri.host || "",
    ipaddress: node["ipaddress"],
    fqdn: node["fqdn"],
  }
end

#node_load_completed(node, _expanded_run_list, _config) ⇒ Object



44
45
46
# File 'lib/chef/compliance/runner.rb', line 44

def node_load_completed(node, _expanded_run_list, _config)
  self.node = node
end

#report(report = nil) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/chef/compliance/runner.rb', line 117

def report(report = nil)
  logger.info "Starting Chef Infra Compliance Phase"
  report ||= generate_report
  # This is invoked at report-time instead of with the normal validations at node loaded,
  # because we want to ensure that it is visible in the output - and not lost in back-scroll.
  warn_for_deprecated_config_values!

  if report.empty?
    logger.error "Compliance report was not generated properly, skipped reporting"
    return
  end

  requested_reporters.each do |reporter_type|
    logger.info "Reporting to #{reporter_type}"
    @reporters[reporter_type].send_report(report)
  end
  logger.info "Chef Infra Compliance Phase Complete"
end

#report_timing_fileObject



378
379
380
# File 'lib/chef/compliance/runner.rb', line 378

def report_timing_file
  ::File.join(Chef::FileCache.create_cache_path("compliance"), "report_timing.json")
end

#report_with_intervalObject



108
109
110
111
112
113
114
115
# File 'lib/chef/compliance/runner.rb', line 108

def report_with_interval
  if interval_seconds_left <= 0
    create_timestamp_file if interval_enabled
    report
  else
    logger.info "Skipping Chef Infra Compliance Phase due to interval settings (next run in #{interval_seconds_left / 60.0} mins)"
  end
end

#reporter(reporter_type) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/chef/compliance/runner.rb', line 274

def reporter(reporter_type)
  case reporter_type
  when "chef-automate"
    require_relative "reporter/automate"
    opts = {
      control_results_limit: node["audit"]["control_results_limit"],
      entity_uuid: node["chef_guid"],
      insecure: node["audit"]["insecure"],
      node_info: node_info,
      run_id: run_id,
      run_time_limit: node["audit"]["run_time_limit"],
    }
    Chef::Compliance::Reporter::Automate.new(opts)
  when "chef-server-automate"
    require_relative "reporter/chef_server_automate"
    opts = {
      control_results_limit: node["audit"]["control_results_limit"],
      entity_uuid: node["chef_guid"],
      insecure: node["audit"]["insecure"],
      node_info: node_info,
      run_id: run_id,
      run_time_limit: node["audit"]["run_time_limit"],
      url: chef_server_automate_url,
    }
    Chef::Compliance::Reporter::ChefServerAutomate.new(opts)
  when "json-file"
    require_relative "reporter/json_file"
    path = node.dig("audit", "json_file", "location")
    Chef::Compliance::Reporter::JsonFile.new(file: path)
  when "audit-enforcer", "compliance-enforcer"
    require_relative "reporter/compliance_enforcer"
    Chef::Compliance::Reporter::ComplianceEnforcer.new
  when "cli"
    require_relative "reporter/cli"
    Chef::Compliance::Reporter::Cli.new
  end
end

#requested_reportersObject



370
371
372
# File 'lib/chef/compliance/runner.rb', line 370

def requested_reporters
  (Array(node["audit"]["reporter"]) + ["cli"]).uniq
end

#run_completed(_node, _run_status) ⇒ Object



69
70
71
72
73
74
75
# File 'lib/chef/compliance/runner.rb', line 69

def run_completed(_node, _run_status)
  return unless enabled?

  logger.debug("#{self.class}##{__method__}: enabling Compliance Phase")

  report_with_interval
end

#run_failed(_exception, _run_status) ⇒ Object



77
78
79
80
81
82
83
84
85
86
# File 'lib/chef/compliance/runner.rb', line 77

def run_failed(_exception, _run_status)
  # If the run has failed because our own validation of compliance
  # phase configuration has failed, we don't want to submit a report
  # because we're still not configured correctly.
  return unless enabled? && @validation_passed

  logger.debug("#{self.class}##{__method__}: enabling Compliance Phase")

  report_with_interval
end

#run_started(run_status) ⇒ Object



56
57
58
# File 'lib/chef/compliance/runner.rb', line 56

def run_started(run_status)
  self.run_id = run_status.run_id
end

#safe_input_collectionObject



366
367
368
# File 'lib/chef/compliance/runner.rb', line 366

def safe_input_collection
  run_context&.input_collection
end

#safe_profile_collectionObject



358
359
360
# File 'lib/chef/compliance/runner.rb', line 358

def safe_profile_collection
  run_context&.profile_collection
end

#safe_waiver_collectionObject



362
363
364
# File 'lib/chef/compliance/runner.rb', line 362

def safe_waiver_collection
  run_context&.waiver_collection
end

#waiver_filesObject



175
176
177
# File 'lib/chef/compliance/runner.rb', line 175

def waiver_files
  Array(node["audit"]["waiver_file"])
end

#waivers_from_collectionObject



148
149
150
# File 'lib/chef/compliance/runner.rb', line 148

def waivers_from_collection
  safe_waiver_collection&.inspec_data || {}
end

#warn_for_deprecated_config_values!Object



99
100
101
102
103
104
105
106
# File 'lib/chef/compliance/runner.rb', line 99

def warn_for_deprecated_config_values!
  deprecated_config_values = (node["audit"].keys & DEPRECATED_CONFIG_VALUES)

  if deprecated_config_values.any?
    values = deprecated_config_values.sort.map { |v| "'#{v}'" }.join(", ")
    logger.warn "audit cookbook config values #{values} are not supported in #{ChefUtils::Dist::Infra::PRODUCT}'s Compliance Phase."
  end
end