Class: Inspec::Runner

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/inspec/runner.rb

Overview

Inspec::Runner coordinates the running of tests and is the main entry point to the application.

Users are expected to insantiate a runner, add targets to be run, and then call the run method:

“‘ r = Inspec::Runner.new() r.add_target(“/path/to/some/profile”) r.add_target(“url/to/some/profile”) r.run “`

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conf = {}) ⇒ Runner

Returns a new instance of Runner.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/inspec/runner.rb', line 35

def initialize(conf = {})
  @rules = []
  @conf = conf.dup
  @conf[:logger] ||= Logger.new(nil)
  @target_profiles = []
  @controls = @conf[:controls] || []
  @depends = @conf[:depends] || []
  @create_lockfile = @conf[:create_lockfile]
  @cache = Inspec::Cache.new(@conf[:vendor_cache])

  # parse any ad-hoc runners reporter formats
  # this has to happen before we load the test_collector
  @conf = Inspec::BaseCLI.parse_reporters(@conf) if @conf[:type].nil?

  @test_collector = @conf.delete(:test_collector) || begin
    require 'inspec/runner_rspec'
    RunnerRspec.new(@conf)
  end

  # list of profile attributes
  @attributes = {}

  load_attributes(@conf)
  configure_transport
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



34
35
36
# File 'lib/inspec/runner.rb', line 34

def attributes
  @attributes
end

#backendObject (readonly)

Returns the value of attribute backend.



34
35
36
# File 'lib/inspec/runner.rb', line 34

def backend
  @backend
end

#rulesObject (readonly)

Returns the value of attribute rules.



34
35
36
# File 'lib/inspec/runner.rb', line 34

def rules
  @rules
end

Instance Method Details

#add_target(target, _opts = []) ⇒ Object

add_target allows the user to add a target whose tests will be run when the user calls the run method.

A target is a path or URL that points to a profile. Using this target we generate a Profile and a ProfileContext. The content (libraries, tests, and attributes) from the Profile are loaded into the ProfileContext.

If the profile depends on other profiles, those profiles will be loaded on-demand when include_content or required_content are called using similar code in Inspec::DSL.

Once the we’ve loaded all of the tests files in the profile, we query the profile for the full list of rules. Those rules are registered with the @test_collector which is ultimately responsible for actually running the tests.

TODO: Deduplicate/clarify the loading code that exists in here, the ProfileContext, the Profile, and Inspec::DSL



196
197
198
199
200
201
202
203
204
# File 'lib/inspec/runner.rb', line 196

def add_target(target, _opts = [])
  profile = Inspec::Profile.for_target(target,
                                       vendor_cache: @cache,
                                       backend: @backend,
                                       controls: @controls,
                                       attributes: @conf[:attributes])
  raise "Could not resolve #{target} to valid input." if profile.nil?
  @target_profiles << profile if supports_profile?(profile)
end

#all_rulesObject

In some places we read the rules off of the runner, in other places we read it off of the profile context. To keep the API’s the same, we provide an #all_rules method here as well.



219
220
221
# File 'lib/inspec/runner.rb', line 219

def all_rules
  @rules
end

#configure_transportObject



65
66
67
68
# File 'lib/inspec/runner.rb', line 65

def configure_transport
  @backend = Inspec::Backend.create(@conf)
  @test_collector.backend = @backend
end

#eval_with_virtual_profile(command) ⇒ Object



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

def eval_with_virtual_profile(command)
  require 'fetchers/mock'
  add_target({ 'inspec.yml' => 'name: inspec-shell' })
  our_profile = @target_profiles.first
  ctx = our_profile.runner_context

  # Load local profile dependencies. This is used in inspec shell
  # to provide access to local profiles that add resources.
  @depends.each do |dep|
    # support for windows paths
    dep = dep.tr('\\', '/')
    Inspec::Profile.for_path(dep, { profile_context: ctx }).load_libraries
  end

  ctx.load(command)
end

#loadObject



78
79
80
81
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
# File 'lib/inspec/runner.rb', line 78

def load
  all_controls = []

  @target_profiles.each do |profile|
    @test_collector.add_profile(profile)
    next unless profile.supports_platform?

    write_lockfile(profile) if @create_lockfile
    profile.locked_dependencies
    profile_context = profile.load_libraries

    profile_context.dependencies.list.values.each do |requirement|
      unless requirement.profile.supports_platform?
        Inspec::Log.warn "Skipping profile: '#{requirement.profile.name}'" \
         " on unsupported platform: '#{@backend.platform.name}/#{@backend.platform.release}'."
        next
      end
      @test_collector.add_profile(requirement.profile)
    end

    @attributes = profile.runner_context.attributes if @attributes.empty?
    tests = profile.collect_tests
    all_controls += tests unless tests.nil?
  end

  all_controls.each do |rule|
    register_rule(rule) unless rule.nil?
  end
end

#load_attributes(options) ⇒ Object

determine all attributes before the execution, fetch data from secrets backend



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/inspec/runner.rb', line 147

def load_attributes(options)
  options[:attributes] ||= {}

  secrets_targets = options[:attrs]
  return options[:attributes] if secrets_targets.nil?

  secrets_targets.each do |target|
    validate_attributes_file_readability!(target)

    secrets = Inspec::SecretsBackend.resolve(target)
    if secrets.nil?
      raise Inspec::Exceptions::SecretsBackendNotFound,
            "Cannot find parser for attributes file '#{target}'. " \
            'Check to make sure file has the appropriate extension.'
    end

    next if secrets.attributes.nil?
    options[:attributes].merge!(secrets.attributes)
  end

  options[:attributes]
end

#register_rules(ctx) ⇒ Object



223
224
225
226
227
228
229
230
231
# File 'lib/inspec/runner.rb', line 223

def register_rules(ctx)
  new_tests = false
  ctx.rules.each do |rule_id, rule|
    next if block_given? && !(yield rule_id, rule)
    new_tests = true
    register_rule(rule)
  end
  new_tests
end

#render_output(run_data) ⇒ Object



114
115
116
117
118
119
120
121
# File 'lib/inspec/runner.rb', line 114

def render_output(run_data)
  return if @conf['reporter'].nil?

  @conf['reporter'].each do |reporter|
    result = Inspec::Reporters.render(reporter, run_data)
    raise Inspec::ReporterError, "Error generating reporter '#{reporter[0]}'" if result == false
  end
end

#reportObject



123
124
125
# File 'lib/inspec/runner.rb', line 123

def report
  Inspec::Reporters.report(@conf['reporter'].first, @run_data)
end

#resetObject



70
71
72
73
74
75
76
# File 'lib/inspec/runner.rb', line 70

def reset
  @test_collector.reset
  @target_profiles.each do |profile|
    profile.runner_context.rules = {}
  end
  @rules = []
end

#run(with = nil) ⇒ Object



108
109
110
111
112
# File 'lib/inspec/runner.rb', line 108

def run(with = nil)
  Inspec::Log.debug "Starting run with targets: #{@target_profiles.map(&:to_s)}"
  load
  run_tests(with)
end

#run_tests(with = nil) ⇒ Object



139
140
141
142
143
144
# File 'lib/inspec/runner.rb', line 139

def run_tests(with = nil)
  @run_data = @test_collector.run(with)
  # dont output anything if we want a report
  render_output(@run_data) unless @conf['report']
  @test_collector.exit_code
end

#supports_profile?(profile) ⇒ Boolean

Returns:

  • (Boolean)


206
207
208
209
210
211
212
213
214
# File 'lib/inspec/runner.rb', line 206

def supports_profile?(profile)
  if !profile.supports_runtime?
    raise 'This profile requires InSpec version '\
         "#{profile..inspec_requirement}. You are running "\
         "InSpec v#{Inspec::VERSION}.\n"
  end

  true
end

#testsObject



61
62
63
# File 'lib/inspec/runner.rb', line 61

def tests
  @test_collector.tests
end

#write_lockfile(profile) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
# File 'lib/inspec/runner.rb', line 127

def write_lockfile(profile)
  return false if !profile.writable?

  if profile.lockfile_exists?
    Inspec::Log.debug "Using existing lockfile #{profile.lockfile_path}"
  else
    Inspec::Log.debug "Creating lockfile: #{profile.lockfile_path}"
    lockfile = profile.generate_lockfile
    File.write(profile.lockfile_path, lockfile.to_yaml)
  end
end