Class: Simp::BeakerHelpers::Inspec

Inherits:
Object
  • Object
show all
Defined in:
lib/simp/beaker_helpers/inspec.rb

Overview

Helpers for working with Inspec

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sut, profile) ⇒ Inspec

Create a new Inspec helper for the specified host against the specified profile

Parameters:

  • sut

    The SUT against which to run

  • profile

    The name of the profile against which to run



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/simp/beaker_helpers/inspec.rb', line 36

def initialize(sut, profile)
  @inspec_version = ENV['BEAKER_inspec_version'] || 'latest'

  @sut = sut

  @sut.install_package('git')

  if @inspec_version == 'latest'
    @sut.install_package('inspec')
  else
    @sut.install_package("inspec-#{@inspec_version}")
  end

  os = fact_on(@sut, 'os.name')
  os_rel = fact_on(@sut, 'os.release.major')

  @profile = "#{os}-#{os_rel}-#{profile}"
  @profile_dir = '/tmp/inspec/inspec_profiles'
  @deps_root = '/tmp/inspec'

  @test_dir = @profile_dir + "/#{@profile}"

  sut.mkdir_p(@profile_dir)

  output_dir = File.absolute_path('sec_results/inspec')

  unless File.directory?(output_dir)
    FileUtils.mkdir_p(output_dir)
  end

  local_profile = File.join(fixtures_path, 'inspec_profiles', %(#{os}-#{os_rel}-#{profile}))
  local_deps = File.join(fixtures_path, 'inspec_deps')

  @result_file = File.join(output_dir, "#{@sut.hostname}-inspec-#{Time.now.to_i}")

  copy_to(@sut, local_profile, @profile_dir)

  if File.exist?(local_deps)
    copy_to(@sut, local_deps, @deps_root)
  end

  # The results of the inspec scan in Hash form
  @results = {}
end

Instance Attribute Details

#deps_rootObject (readonly)

Returns the value of attribute deps_root.



11
12
13
# File 'lib/simp/beaker_helpers/inspec.rb', line 11

def deps_root
  @deps_root
end

#profileObject (readonly)

Returns the value of attribute profile.



9
10
11
# File 'lib/simp/beaker_helpers/inspec.rb', line 9

def profile
  @profile
end

#profile_dirObject (readonly)

Returns the value of attribute profile_dir.



10
11
12
# File 'lib/simp/beaker_helpers/inspec.rb', line 10

def profile_dir
  @profile_dir
end

Class Method Details

.enable_repo_on(suts) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/simp/beaker_helpers/inspec.rb', line 13

def self.enable_repo_on(suts)
  parallel = (ENV['BEAKER_SIMP_parallel'] == 'yes')
  block_on(suts, :run_in_parallel => parallel) do |sut|
    repo_manifest = create_yum_resource(
      'chef-current',
      {
        :baseurl => "https://packages.chef.io/repos/yum/current/el/#{fact_on(sut,'os.release.major')}/$basearch",
        :gpgkeys => ['https://packages.chef.io/chef.asc']
      }
    )

    apply_manifest_on(sut, repo_manifest, :catch_failures => true)
  end
end

.process_inspec_results(results) ⇒ Hash

Process the results of an InSpec run

Returns:

  • (Hash)

    A Hash of statistics and a formatted report



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/simp/beaker_helpers/inspec.rb', line 158

def self.process_inspec_results(results)
  require 'highline'

  HighLine.colorize_strings

  stats = {
    # Legacy metrics counters for backwards compatibility
    :failed     => 0,
    :passed     => 0,
    :skipped    => 0,
    :overridden => 0,
    # End legacy stuff
    :global   => {
      :failed     => [],
      :passed     => [],
      :skipped    => [],
      :overridden => []
    },
    :score    => 0,
    :report   => nil,
    :profiles => {}
  }

  if results.is_a?(String)
    if File.readable?(results)
      profiles = JSON.load(File.read(results))['profiles']
    else
      fail("Error: Could not read results file at #{results}")
    end
  elsif results.is_a?(Hash)
    profiles = results['profiles']
  else
    fail("Error: first argument must be a String path to a file or a Hash")
  end

  if !profiles || profiles.empty?
    fail("Error: Could not find 'profiles' in the passed results")
  end

  profiles.each do |profile|
    profile_name = profile['name']

    next unless profile_name

    stats[:profiles][profile_name] = {
      :controls => {}
    }

    profile['controls'].each do |control|
      title = control['title']

      next unless title

      base_title = title.scan(/.{1,60}\W|.{1,60}/).map(&:strip).join("\n           ")

      if control['results'] && (control['results'].size > 1)
        control['results'].each do |result|
          control_title = " => { #{result['code_desc']} }"

          full_title = title + control_title
          formatted_title = base_title + control_title

          stats[:profiles][profile_name][:controls][full_title] = {}

          stats[:profiles][profile_name][:controls][full_title][:formatted_title] = formatted_title

          if result['status'] =~ /^fail/
            status = :failed
            color = 'red'
          else
            status = :passed
            color = 'green'
          end

          stats[:global][status] << formatted_title.color

          stats[:profiles][profile_name][:controls][full_title][:status] = status
          stats[:profiles][profile_name][:controls][full_title][:source] = control['source_location']['ref']
        end
      else
        formatted_title = base_title

        stats[:profiles][profile_name][:controls][title] = {}

        stats[:profiles][profile_name][:controls][title][:formatted_title] = formatted_title

        if control['results'] && !control['results'].empty?
          status = :passed
          color = 'green'

          control['results'].each do |result|
            if results['status'] =~ /^fail/
              status = :failed
              color = 'red'
            end
          end

        else
          status = :skipped
        end

        stats[:global][status] << formatted_title.color

        stats[:profiles][profile_name][:controls][title][:status] = status
        stats[:profiles][profile_name][:controls][title][:source] = control['source_location']['ref']
      end
    end
  end

  valid_checks = stats[:global][:failed] + stats[:global][:passed]
  stats[:global][:skipped].dup.each do |skipped|
    if valid_checks.include?(skipped)
      stats[:global][:overridden] << skipped
      stats[:global][:skipped].delete(skipped)
    end
  end

  status_colors = {
    :failed     => 'red',
    :passed     => 'green',
    :skipped    => 'yellow',
    :overridden => 'white'
  }

  report = []

  stats[:profiles].keys.each do |profile|
    report << "Profile: #{profile}"

    stats[:profiles][profile][:controls].each do |control|
      control_info = control.last

      report << "\n  Control: #{control_info[:formatted_title]}"

      if control_info[:status] == :skipped && stats[:global][:overridden].include?(control.first)
        control_info[:status] = :overridden
      end

      report << "    Status: #{control_info[:status].to_s.send(status_colors[control_info[:status]])}"
      report << "    File: #{control_info[:source]}" if control_info[:source]
    end

    report << "\n"
  end

  num_passed     = stats[:global][:passed].count
  num_failed     = stats[:global][:failed].count
  num_skipped    = stats[:global][:skipped].count
  num_overridden = stats[:global][:overridden].count

  # Backwards compat values
  stats[:passed]     = num_passed
  stats[:failed]     = num_failed
  stats[:skipped]    = num_skipped
  stats[:overridden] = num_overridden

  report << "Statistics:"
  report << "  * Passed: #{num_passed.to_s.green}"
  report << "  * Failed: #{num_failed.to_s.red}"
  report << "  * Skipped: #{num_skipped.to_s.yellow}"

  score = 0
  if (stats[:global][:passed].count + stats[:global][:failed].count) > 0
    score = ((stats[:global][:passed].count.to_f/(stats[:global][:passed].count + stats[:global][:failed].count)) * 100.0).round(0)
  end

  report << "\n Score: #{score}%"

  stats[:score] = score
  stats[:report] = report.join("\n")

  return stats
end

Instance Method Details

#process_inspec_resultsObject



150
151
152
# File 'lib/simp/beaker_helpers/inspec.rb', line 150

def process_inspec_results
  self.class.process_inspec_results(@results)
end

#runObject

Run the inspec tests and record the results



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/simp/beaker_helpers/inspec.rb', line 82

def run
  sut_inspec_results = '/tmp/inspec_results.json'

  inspec_version = Gem::Version.new(on(@sut, 'inspec --version').output.lines.first.strip)

  # See: https://github.com/inspec/inspec/pull/3935
  if inspec_version <= Gem::Version.new('3.9.0')
    inspec_cmd = "inspec exec '#{@test_dir}' --reporter json > #{sut_inspec_results}"
  else
    inspec_cmd = "inspec exec '#{@test_dir}' --chef-license accept --reporter json > #{sut_inspec_results}"
  end

  result = on(@sut, inspec_cmd, :accept_all_exit_codes => true)

  tmpdir = Dir.mktmpdir
  begin
    Dir.chdir(tmpdir) do
      scp_from(@sut, sut_inspec_results, '.')

      local_inspec_results = File.basename(sut_inspec_results)

      if File.exist?(local_inspec_results)
        begin
          # The output is occasionally broken from past experience. Need to
          # fetch the line that actually looks like JSON
          inspec_json = File.read(local_inspec_results).lines.find do |line|
            line.strip!

            line.start_with?('{') && line.end_with?('}')
          end

          @results = JSON.load(inspec_json) if inspec_json
        rescue JSON::ParserError, JSON::GeneratorError
          @results = nil
        end
      end
    end
  ensure
    FileUtils.remove_entry_secure tmpdir
  end

  if @results.nil? || @results.empty?
    File.open(@result_file + '.err', 'w') do |fh|
      fh.puts(result.stderr.strip)
    end

    err_msg = ["Error running inspec command #{inspec_cmd}"]
    err_msg << "Error captured in #{@result_file}" + '.err'

    fail(err_msg.join("\n"))
  end
end

#write_report(report) ⇒ Object

Output the report

Parameters:

  • report

    The inspec results Hash



140
141
142
143
144
145
146
147
148
# File 'lib/simp/beaker_helpers/inspec.rb', line 140

def write_report(report)
  File.open(@result_file + '.json', 'w') do |fh|
    fh.puts(JSON.pretty_generate(@results))
  end

  File.open(@result_file + '.report', 'w') do |fh|
    fh.puts(report[:report].uncolor)
  end
end