Signed-off-by: Miah Johnson <miah@chia-pet.org>
This commit is contained in:
Miah Johnson 2019-07-08 17:20:30 -07:00
parent badb7e6b89
commit a4f4fe5231
292 changed files with 1346 additions and 903 deletions

View file

@ -136,6 +136,7 @@ namespace :test do
task :resources do
tests = Dir["test/unit/resource/*_test.rb"]
return if tests.empty?
sh(Gem.ruby, "test/docker_test.rb", *tests)
end
@ -153,11 +154,11 @@ namespace :test do
key_files = ENV["key_files"] || File.join(ENV["HOME"], ".ssh", "id_rsa")
sh_cmd = "bin/inspec exec #{tests_path}/"
sh_cmd += ENV["test"] ? "#{ENV['test']}_spec.rb" : "*"
sh_cmd += ENV["test"] ? "#{ENV["test"]}_spec.rb" : "*"
sh_cmd += " --sudo" unless args[:target].split("@")[0] == "root"
sh_cmd += " -t ssh://#{args[:target]}"
sh_cmd += " --key_files=#{key_files}"
sh_cmd += " --format=#{ENV['format']}" if ENV["format"]
sh_cmd += " --format=#{ENV["format"]}" if ENV["format"]
sh("sh", "-c", sh_cmd)
end
@ -217,7 +218,7 @@ namespace :test do
end
end
desc "Perform AWS Integration Tests"
task aws: [:'aws:default', :'aws:minimal']
task aws: %i{aws:default aws:minimal}
namespace :azure do
# Specify the directory for the integration tests
@ -268,7 +269,7 @@ namespace :test do
suffix = "#{suffix}"
VARS
content << "location = \"#{ENV['AZURE_LOCATION']}\"\n" if ENV["AZURE_LOCATION"]
content << "location = \"#{ENV["AZURE_LOCATION"]}\"\n" if ENV["AZURE_LOCATION"]
File.write(tf_vars_file, content)
end
@ -359,6 +360,7 @@ end
# @param [Type] msg the message to display if the command is missing
def require_command(x, msg = nil)
return if system("command -v #{x} || exit 1")
msg ||= "Please install it first!"
puts "\033[31;1mCan't find command #{x.inspect}. #{msg}\033[0m"
exit 1
@ -371,6 +373,7 @@ end
def require_env(x, msg = nil)
exists = `env | grep "^#{x}="`
return unless exists.empty?
puts "\033[31;1mCan't find environment variable #{x.inspect}. #{msg}\033[0m"
exit 1
end

View file

@ -13,7 +13,7 @@ Gem::Specification.new do |spec|
spec.license = "Apache-2.0"
spec.files = %w{README.md LICENSE} + Dir.glob("{bin,lib,etc}/**/*", File::FNM_DOTMATCH)
.reject { |f| File.directory?(f) || f =~ /aws|azure|gcp/ || f =~ %r{lib/plugins/.*/test/} }
.reject { |f| File.directory?(f) || f =~ /aws|azure|gcp/ || f =~ %r{lib/plugins/.*/test/} }
spec.require_paths = ["lib"]

View file

@ -18,7 +18,7 @@ Gem::Specification.new do |spec|
).reject { |f| File.directory?(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
.reject { |f| File.directory?(f) || f =~ %r{lib/plugins/.*/test/} }
.reject { |f| File.directory?(f) || f =~ %r{lib/plugins/.*/test/} }
spec.require_paths = ["lib"]
spec.required_ruby_version = ">= 2.4"

View file

@ -35,10 +35,11 @@ module Supermarket
def self.info(profile, supermarket_url = SUPERMARKET_URL)
_tool_owner, tool_name = profile_name("supermarket://#{profile}")
return if tool_name.nil? || tool_name.empty?
# Tool name in Supermarket URL is downcased so we need to downcase
url = "#{supermarket_url}/api/v1/tools/#{tool_name.downcase}"
_success, data = get(url, {})
JSON.parse(data) if !data.nil?
JSON.parse(data) unless data.nil?
rescue JSON::ParserError
nil
end

View file

@ -20,7 +20,7 @@ module Supermarket
headline("Available profiles:")
supermarket_profiles.each do |p|
li("#{p['tool_name']} #{mark_text(p['tool_owner'] + '/' + p['slug'])}")
li("#{p["tool_name"]} #{mark_text(p["tool_owner"] + "/" + p["slug"])}")
end
end
@ -48,7 +48,7 @@ module Supermarket
# check that the profile is available
supermarket_profiles = Supermarket::API.profiles
found = supermarket_profiles.select do |p|
profile == "#{p['tool_owner']}/#{p['slug']}"
profile == "#{p["tool_owner"]}/#{p["slug"]}"
end
if found.empty?
@ -58,11 +58,11 @@ module Supermarket
# load details for the specific profile
info = Supermarket::API.info(profile)
puts "#{mark_text('name: ')} #{info['slug']}"
puts "#{mark_text('owner:')} #{info['owner']}"
puts "#{mark_text('url: ')} #{info['source_url']}"
puts "#{mark_text("name: ")} #{info["slug"]}"
puts "#{mark_text("owner:")} #{info["owner"]}"
puts "#{mark_text("url: ")} #{info["source_url"]}"
puts
puts "#{mark_text('description: ')} #{info['description']}"
puts "#{mark_text("description: ")} #{info["description"]}"
end
end

View file

@ -17,6 +17,7 @@ module Supermarket
end
return nil unless supermarket_uri
return nil unless Supermarket::API.exist?(supermarket_uri, supermarket_server)
tool_info = Supermarket::API.find(supermarket_uri, supermarket_server)
resolve_next(tool_info["tool_source_url"], opts)
rescue URI::Error

View file

@ -89,10 +89,12 @@ module Fetchers
command_string = "git ls-remote \"#{@remote_url}\" \"#{ref_name}*\""
cmd = shellout(command_string)
raise "Error running '#{command_string}': #{cmd.stderr}" unless cmd.exitstatus == 0
ref = parse_ls_remote(cmd.stdout, ref_name)
if !ref
unless ref
raise "Unable to resolve #{ref_name} to a specific git commit for #{@remote_url}"
end
ref
end

View file

@ -7,6 +7,7 @@ module Fetchers
def self.resolve(target)
return nil unless target.is_a? Hash
new(target)
end

View file

@ -29,6 +29,7 @@ module Fetchers
uri = URI.parse(target)
return nil if uri.nil? || uri.scheme.nil?
return nil unless %{ http https }.include? uri.scheme
target = transform(target)
opts[:username] = username if username
opts[:password] = password if password
@ -121,6 +122,7 @@ module Fetchers
def parse_uri(target)
return URI.parse(target) if target.is_a?(String)
URI.parse(target[:url])
end
@ -150,7 +152,7 @@ module Fetchers
end
def download_automate2_archive_to_temp
return @temp_archive_path if !@temp_archive_path.nil?
return @temp_archive_path unless @temp_archive_path.nil?
Inspec::Log.debug("Fetching URL: #{@target}")
json = {
@ -189,7 +191,8 @@ module Fetchers
# Downloads archive to temporary file with side effect :( of setting @archive_type
def download_archive_to_temp
return @temp_archive_path if !@temp_archive_path.nil?
return @temp_archive_path unless @temp_archive_path.nil?
Inspec::Log.debug("Fetching URL: #{@target}")
remote = open_via_uri(@target)
@archive_type = file_type_from_remote(remote) # side effect :(
@ -262,7 +265,7 @@ module Fetchers
end
unless keys_missing_values.empty?
raise "Unable to fetch profile - the following HTTP headers have no value: " \
"#{keys_missing_values.join(', ')}"
"#{keys_missing_values.join(", ")}"
end
end
end

View file

@ -22,6 +22,7 @@ module Inspec
# the Ruby stdlib for a better experience.
def local_transport?
return false unless defined?(Train::Transports::Local)
backend.is_a?(Train::Transports::Local::Connection)
end

View file

@ -10,9 +10,11 @@ require "inspec/utils/deprecation/global_method"
class Thor::Arguments
def parse_array(_name)
return shift if peek.is_a?(Array)
array = []
while current_is_value?
break unless @parsing_options
array << shift
end
array
@ -157,7 +159,7 @@ module Inspec
next if data.nil?
data = "\e[1m\e[#{color}m#{data}\e[0m"
str << format("#{' ' * indent}%-10s %s\n", item.to_s.capitalize + ":", data)
str << format("#{" " * indent}%-10s %s\n", item.to_s.capitalize + ":", data)
end
str
end
@ -218,6 +220,7 @@ module Inspec
def suppress_log_output?(opts)
return false if opts["reporter"].nil?
match = %w{json json-min json-rspec json-automate junit html yaml documentation progress} & opts["reporter"].keys
unless match.empty?
match.each do |m|

View file

@ -124,7 +124,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
else
%w{location profile controls timestamp valid}.each do |item|
puts format("%-12s %s", item.to_s.capitalize + ":",
mark_text(result[:summary][item.to_sym]))
mark_text(result[:summary][item.to_sym]))
end
puts
@ -148,8 +148,8 @@ class Inspec::InspecCLI < Inspec::BaseCLI
puts
puts format("Summary: %s%d errors%s, %s%d warnings%s",
red, result[:errors].length, rst,
yellow, result[:warnings].length, rst)
red, result[:errors].length, rst,
yellow, result[:warnings].length, rst)
end
end
exit 1 unless result[:summary][:valid]
@ -375,7 +375,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
puts Inspec::Schema.json(name)
rescue StandardError => e
puts e
puts "Valid schemas are #{Inspec::Schema.names.join(', ')}"
puts "Valid schemas are #{Inspec::Schema.names.join(", ")}"
end
desc "version", "prints the version of this tool"
@ -410,6 +410,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
runner.load
return :ruby_eval, res if runner.all_rules.empty?
return :rspec_run, runner.run_tests # rubocop:disable Style/RedundantReturn
end
end

View file

@ -60,6 +60,7 @@ module Inspec
def diagnose
return unless self[:diagnose]
puts "InSpec version: #{Inspec::VERSION}"
puts "Train version: #{Train::VERSION}"
puts "Command line configuration:"
@ -159,6 +160,7 @@ module Inspec
unless transport_name
raise ArgumentError, "Could not recognize a backend from the target #{final_options[:target]} - use a URI format with the backend name as the URI schema. Example: 'ssh://somehost.com' or 'transport://credset' or 'transport://' if credentials are provided outside of InSpec."
end
credentials[:backend] = transport_name.to_s # these are indeed stored in Train as Strings.
end
@ -185,6 +187,7 @@ module Inspec
def _utc_find_credset_name(_credentials, transport_name)
return nil unless final_options[:target]
match = final_options[:target].match(%r{^#{transport_name}://(?<credset_name>[\w\d\-]+)$})
match ? match[:credset_name] : nil
end
@ -196,6 +199,7 @@ module Inspec
# Regardless of our situation, end up with a readable IO object
def resolve_cfg_io(cli_opts, cfg_io)
raise(ArgumentError, "Inspec::Config must use an IO to read from") if cfg_io && !cfg_io.respond_to?(:read)
cfg_io ||= check_for_piped_config(cli_opts)
return cfg_io if cfg_io
@ -211,6 +215,7 @@ module Inspec
return nil unless cli_opt
return nil unless cli_opt == "-"
# This warning is here so that if a user invokes inspec with --config=-,
# they will have an explanation for why it appears to hang.
Inspec::Log.warn "Reading JSON config from standard input" if STDIN.tty?
@ -287,13 +292,14 @@ module Inspec
valid_fields = %w{version cli_options credentials compliance reporter}.sort
@cfg_file_contents.keys.each do |seen_field|
unless valid_fields.include?(seen_field)
raise Inspec::ConfigError::Invalid, "Unrecognized top-level configuration field #{seen_field}. Recognized fields: #{valid_fields.join(', ')}"
raise Inspec::ConfigError::Invalid, "Unrecognized top-level configuration field #{seen_field}. Recognized fields: #{valid_fields.join(", ")}"
end
end
end
def validate_reporters!(reporters)
return if reporters.nil?
# TODO: move this into a reporter plugin type system
valid_types = %w{
automate
@ -313,6 +319,7 @@ module Inspec
raise NotImplementedError, "'#{reporter_name}' is not a valid reporter type." unless valid_types.include?(reporter_name)
next unless reporter_name == "automate"
%w{token url}.each do |option|
raise Inspec::ReporterError, "You must specify a automate #{option} via the config file." if reporter_config[option].nil?
end
@ -410,6 +417,7 @@ module Inspec
%w{password sudo-password}.each do |option_name|
snake_case_option_name = option_name.tr("-", "_").to_s
next unless options[snake_case_option_name] == -1 # Thor sets -1 for missing value - see #1918
raise ArgumentError, "Please provide a value for --#{option_name}. For example: --#{option_name}=hello."
end

View file

@ -216,6 +216,7 @@ module Inspec
return if @skip_only_if_eval == true
return if block.yield == true
# Apply `set_skip_rule` for other rules in the same file
profile_context_owner.rules.values.each do |r|
sources_match = r.source_file == block.source_location[0]

View file

@ -49,6 +49,7 @@ module Inspec
#
def exists?(key)
return false if key.nil? || key.empty?
path = base_path_for(key)
File.directory?(path) || File.exist?("#{path}.tar.gz") || File.exist?("#{path}.zip")
end

View file

@ -71,6 +71,7 @@ module Inspec
def to_array
return [] if @dep_list.nil?
@dep_list.map do |_k, v|
v.to_hash
end.compact
@ -85,6 +86,7 @@ module Inspec
#
def vendor(dependencies)
return nil if dependencies.nil? || dependencies.empty?
@dep_list = Resolver.resolve(dependencies, @cache, @cwd, @backend)
end
end

View file

@ -18,6 +18,7 @@ module Inspec
parsed_content = YAML.load(content)
version = parsed_content["lockfile_version"]
raise "No lockfile_version set in #{path}!" if version.nil?
validate_lockfile_version!(version.to_i)
new(parsed_content)
end

View file

@ -21,16 +21,16 @@ module Inspec
}
new(dep[:name],
dep[:version],
config,
opts.merge(dep))
dep[:version],
config,
opts.merge(dep))
end
def self.from_lock_entry(entry, config, opts = {})
req = new(entry[:name],
entry[:version_constraints],
config,
entry[:resolved_source].merge(backend: config[:backend]).merge(opts))
entry[:version_constraints],
config,
entry[:resolved_source].merge(backend: config[:backend]).merge(opts))
locked_deps = []
Array(entry[:dependencies]).each do |dep_entry|
@ -86,7 +86,7 @@ module Inspec
"version_constraints" => version_constraints,
}
if !dependencies.empty?
unless dependencies.empty?
h["dependencies"] = dependencies.map(&:to_hash)
end
@ -115,6 +115,7 @@ module Inspec
# load the profile for the requirement
def profile
return @profile unless @profile.nil?
opts = @opts.dup
opts[:backend] = @backend
opts[:runner_conf] = Inspec::Config.cached

View file

@ -37,7 +37,7 @@ module Inspec
problem_cookbook = if top_level
"the inspec.yml for this profile."
else
"the dependency information for #{path_string.split(' ').last}"
"the dependency information for #{path_string.split(" ").last}"
end
raise Inspec::DuplicateDep, "The dependency #{dep.name} is listed twice in #{problem_cookbook}"
else
@ -68,13 +68,13 @@ module Inspec
new_seen_items[dep.resolved_source] = true
if !dep.source_satisfies_spec?
unless dep.source_satisfies_spec?
raise Inspec::UnsatisfiedVersionSpecification, "The profile #{dep.name} from #{dep.resolved_source} has a version #{dep.source_version} which doesn't match #{dep.version_constraints}"
end
Inspec::Log.debug("Adding dependency #{dep.name} (#{dep.resolved_source})")
graph[dep.name] = dep
if !dep.dependencies.empty?
unless dep.dependencies.empty?
resolve(dep.dependencies, false, new_seen_items.dup, new_path_string)
end
end

View file

@ -12,6 +12,7 @@ module Inspec
# @return [nil]
def one(&block)
return unless block_given?
instance_eval(&block)
@action.call("describe.one", @checks, nil)
end

View file

@ -68,7 +68,7 @@ module Inspec::DSL
context = dep_entry.profile.runner_context
# if we don't want all the rules, then just make 1 pass to get all rule_IDs
# that we want to keep from the original
filter_included_controls(context, dep_entry.profile, &block) if !opts[:include_all]
filter_included_controls(context, dep_entry.profile, &block) unless opts[:include_all]
# interpret the block and skip/modify as required
context.load(block) if block_given?
bind_context.add_subcontext(context)

View file

@ -10,7 +10,7 @@ module Inspec
def require(path)
rbpath = path + ".rb"
return __ruby_require(path) if !@require_loader.exists?(rbpath)
return __ruby_require(path) unless @require_loader.exists?(rbpath)
return false if @require_loader.loaded?(rbpath)
# This is equivalent to calling `require 'lib'` with lib on disk.

View file

@ -23,8 +23,8 @@ module Inspec
end
def print_and_exit!
exit_no_shell if !have_shell?
exit_no_completion if !have_shell_completion?
exit_no_shell unless have_shell?
exit_no_completion unless have_shell_completion?
print_completion_for_shell
print_detection_warning($stdout) if @detected
@ -77,7 +77,7 @@ module Inspec
#
# inspec env SHELLNAME
#
# Currently supported shells are: #{shells_with_completions.join(', ')}
# Currently supported shells are: #{shells_with_completions.join(", ")}
#
EOF
end
@ -98,7 +98,7 @@ module Inspec
#
# inspec env SHELLNAME
#
# Currently supported shells are: #{shells_with_completions.join(', ')}
# Currently supported shells are: #{shells_with_completions.join(", ")}
EOF
exit 1
end

View file

@ -11,12 +11,13 @@ module Inspec
end
end
NON_FETCHER_KEYS = [:name, :version_constraint, :cwd, :backend, :cache, :sha256].freeze
NON_FETCHER_KEYS = %i{name version_constraint cwd backend cache sha256}.freeze
def fetcher_specified?(target)
# Only set a default for Hash-based (i.e. from
# inspec.yml/inspec.lock) targets
return true if !target.respond_to?(:keys)
return true unless target.respond_to?(:keys)
!(target.keys - NON_FETCHER_KEYS).empty?
end
@ -31,6 +32,7 @@ module Inspec
if version != 1
raise "Only fetcher version 1 is supported!"
end
Inspec::Plugins::Fetcher
end
end

View file

@ -21,8 +21,7 @@ module Inspec
end
end
def initialize(_path)
end
def initialize(_path); end
# List all files that are offered.
#
@ -80,12 +79,14 @@ module Inspec
def read(file)
return nil unless files.include?(file)
return nil unless File.file?(file)
File.read(file)
end
def binread(file)
return nil unless files.include?(file)
return nil unless File.file?(file)
File.binread(file)
end
end
@ -133,10 +134,12 @@ module Inspec
def read_from_zip(file)
return nil unless @files.include?(file)
res = nil
walk_zip(@path) do |io|
while (entry = io.get_next_entry)
next unless file == entry.name
res = io.read
break
end
@ -172,6 +175,7 @@ module Inspec
walk_tar(@path) do |files|
files.each do |file|
next unless @files.include?(file.full_name)
final_path = File.join(destination_path, file.full_name)
# This removes the top level directory (and any other files) to ensure
@ -199,11 +203,13 @@ module Inspec
def read_from_tar(file)
return nil unless @files.include?(file)
res = nil
# NB `TarReader` includes `Enumerable` beginning with Ruby 2.x
walk_tar(@path) do |tar|
tar.each do |entry|
next unless entry.file? && [file, "./#{file}"].include?(entry.full_name)
res = entry.read
break
end
@ -235,16 +241,17 @@ module Inspec
# PAX-formatted tar files. Do not do any translation of the path if the
# path is an absolute path.
@files = parent.files
.find_all { |x| x.start_with?(prefix) && x != prefix }
.map { |x| x[prefix.length..-1] }
.map do |x|
path = Pathname.new(x)
path.absolute? ? path.to_s : path.relative_path_from(Pathname.new(".")).to_s
end
.find_all { |x| x.start_with?(prefix) && x != prefix }
.map { |x| x[prefix.length..-1] }
.map do |x|
path = Pathname.new(x)
path.absolute? ? path.to_s : path.relative_path_from(Pathname.new(".")).to_s
end
end
def abs_path(file)
return nil if file.nil?
prefix + file
end
@ -278,12 +285,14 @@ module Inspec
def get_folder_prefix(fs)
return get_files_prefix(fs) if fs.length == 1
first, *rest = fs
pre = prefix_candidate_for(first)
if rest.all? { |i| i.start_with? pre }
return get_folder_prefix(rest)
end
get_files_prefix(fs)
end
@ -303,6 +312,7 @@ module Inspec
new_pre = get_prefix(rest)
return new_pre if pre.start_with? new_pre
# edge case: completely different prefixes; retry prefix detection
a = File.dirname(pre + "a")
b = File.dirname(new_pre + "b")

View file

@ -49,6 +49,7 @@ module Inspec::Formatters
end
next if e.is_a? RSpec::Expectations::ExpectationNotMetError
hash[:exception] = e.class.name
hash[:backtrace] = e.backtrace
end
@ -101,6 +102,7 @@ module Inspec::Formatters
all_unique_controls.each do |control|
next unless control[:results]
if control[:results].any? { |r| r[:status] == "failed" }
failed += 1
elsif control[:results].any? { |r| r[:status] == "skipped" }
@ -185,6 +187,7 @@ module Inspec::Formatters
# the proper report.
def platform(field)
return nil if @backend.nil?
begin
@backend.platform[field]
rescue Train::Error => e
@ -195,6 +198,7 @@ module Inspec::Formatters
def backend_target
return nil if @backend.nil?
connection = @backend.backend
connection.respond_to?(:uri) ? connection.uri : nil
end
@ -218,6 +222,7 @@ module Inspec::Formatters
def example2control(example)
profile = profile_from_example(example)
return nil unless profile&.[](:controls)
profile[:controls].find { |x| x[:id] == example[:id] }
end

View file

@ -12,6 +12,7 @@ module Inspec::Impact
# return if its a number
return value if is_number?(value)
raise Inspec::ImpactError, "'#{value}' is not a valid impact name. Valid impact names: none, low, medium, high, critical." unless IMPACT_SCORES.key?(value.downcase)
IMPACT_SCORES[value]
end
@ -25,6 +26,7 @@ module Inspec::Impact
def self.string_from_impact(value)
value = value.to_f
raise Inspec::ImpactError, "'#{value}' is not a valid impact score. Valid impact scores: [0.0 - 1.0]." if value < 0 || value > 1
IMPACT_SCORES.reverse_each do |name, impact|
return name if value >= impact
end

View file

@ -169,11 +169,12 @@ module Inspec
data = Inspec::SecretsBackend.resolve(path)
if data.nil?
raise Inspec::Exceptions::SecretsBackendNotFound,
"Cannot find parser for inputs file '#{path}'. " \
"Check to make sure file has the appropriate extension."
"Cannot find parser for inputs file '#{path}'. " \
"Check to make sure file has the appropriate extension."
end
next if data.inputs.nil?
data.inputs.each do |input_name, input_value|
evt = Inspec::Input::Event.new(
value: input_value,
@ -190,14 +191,14 @@ module Inspec
def validate_inputs_file_readability!(path)
unless File.exist?(path)
raise Inspec::Exceptions::InputsFileDoesNotExist,
"Cannot find input file '#{path}'. " \
"Check to make sure file exists."
"Cannot find input file '#{path}'. " \
"Check to make sure file exists."
end
unless File.readable?(path)
raise Inspec::Exceptions::InputsFileNotReadable,
"Cannot read input file '#{path}'. " \
"Check to make sure file is readable."
"Cannot read input file '#{path}'. " \
"Check to make sure file is readable."
end
true
@ -260,13 +261,13 @@ module Inspec
# These class methods are convenience methods so you don't always
# have to call #instance when calling the registry
[
:find_or_register_input,
:register_profile_alias,
:list_inputs_for_profile,
:list_potential_input_names_for_profile,
:bind_profile_inputs,
].each do |meth|
%i{
find_or_register_input
register_profile_alias
list_inputs_for_profile
list_potential_input_names_for_profile
bind_profile_inputs
}.each do |meth|
define_singleton_method(meth) do |*args|
instance.send(meth, *args)
end

View file

@ -74,6 +74,7 @@ module Inspec
%w{name version}.each do |field|
next unless params[field.to_sym].nil?
errors.push("Missing profile #{field} in #{ref}")
end
@ -89,6 +90,7 @@ module Inspec
%w{title summary maintainer copyright license}.each do |field|
next unless params[field.to_sym].nil?
warnings.push("Missing profile #{field} in #{ref}")
end
@ -151,8 +153,8 @@ module Inspec
when nil then nil
else
Inspec.deprecate(:supports_syntax,
"Do not use deprecated `supports: #{x}` syntax. Instead use:\n"\
"supports:\n - os-family: #{x}\n\n")
"Do not use deprecated `supports: #{x}` syntax. Instead use:\n"\
"supports:\n - os-family: #{x}\n\n")
{ :'os-family' => x } # rubocop:disable Style/HashSyntax
end
end
@ -182,12 +184,14 @@ module Inspec
# Crudely slug the target to not contain slashes, to avoid breaking
# unit tests that look for warning sequences
return if original_target.to_s.empty?
metadata.params[:title] = "tests from #{original_target}"
metadata.params[:name] = metadata.params[:title].gsub(%r{[\/\\]}, ".")
end
def self.finalize(metadata, profile_id, options, logger = nil)
return nil if metadata.nil?
param = metadata.params || {}
options ||= {}
param["version"] = param["version"].to_s unless param["version"].nil?

View file

@ -14,7 +14,7 @@ module Inspec
::MethodSource.expression_at(src.lines, location[:line]).force_encoding("utf-8")
rescue SyntaxError => e
raise ::MethodSource::SourceNotFoundError,
"Could not parse source at #{location[:ref]}:#{location[:line]}: #{e.message}"
"Could not parse source at #{location[:ref]}:#{location[:line]}: #{e.message}"
end
end
end

View file

@ -33,6 +33,7 @@ module Inspec
descriptions.each do |label, text|
if label == :default
next if text.nil? || (text == "") # don't render empty/nil desc
res.push " desc #{prettyprint_text(text, 2)}"
else
res.push " desc #{label.to_s.inspect}, #{prettyprint_text(text, 2)}"
@ -52,6 +53,7 @@ module Inspec
def print_ref(x)
return x.inspect if x.is_a?(String)
raise "Cannot process the ref: #{x}" unless x.is_a?(Hash)
"(" + x.inspect + ")"
end
@ -62,7 +64,8 @@ module Inspec
# @return [String] pretty-printed textblock
def prettyprint_text(s, depth)
txt = s.to_s.inspect.gsub('\n', "\n")
return txt if !txt.include?("\n")
return txt unless txt.include?("\n")
middle = indent(txt[1..-2], depth + 2)
txt[0] + "\n" + middle + "\n" + " " * depth + txt[-1]
end

View file

@ -62,7 +62,8 @@ module Inspec
end
def to_ruby
return rb_skip if !skip.nil?
return rb_skip unless skip.nil?
rb_describe
end
@ -72,6 +73,7 @@ module Inspec
def resource
return nil if qualifier.empty? || qualifier[0].empty? || qualifier[0][0].empty?
qualifier[0][0]
end

View file

@ -309,9 +309,10 @@ module Inspec
def to_hash
as_hash = { name: name, options: {} }
[:description, :title, :identifier, :type, :required, :value].each do |field|
%i{description title identifier type required value}.each do |field|
val = send(field)
next if val.nil?
as_hash[:options][field] = val
end
as_hash
@ -372,11 +373,11 @@ module Inspec
invalid_type = false
if type_req == "Regexp"
invalid_type = true if !valid_regexp?(proposed_value)
invalid_type = true unless valid_regexp?(proposed_value)
elsif type_req == "Numeric"
invalid_type = true if !valid_numeric?(proposed_value)
invalid_type = true unless valid_numeric?(proposed_value)
elsif type_req == "Boolean"
invalid_type = true if ![true, false].include?(proposed_value)
invalid_type = true unless [true, false].include?(proposed_value)
elsif proposed_value.is_a?(Module.const_get(type_req)) == false
# TODO: why is this case here?
invalid_type = true
@ -400,7 +401,7 @@ module Inspec
"Regex" => "Regexp",
}
type_req = abbreviations[type_req] if abbreviations.key?(type_req)
if !VALID_TYPES.include?(type_req)
unless VALID_TYPES.include?(type_req)
error = Inspec::Input::TypeError.new
error.input_type = type_req
raise error, "Type '#{error.input_type}' is not a valid input type."

View file

@ -2,10 +2,12 @@ module Inspec
class List < Value
def map
raise "Inspec::List.map needs to be called with a block" unless block_given?
t = List.new
t.qualifier = [["x"]]
yield(t)
return if t.qualifier == [["x"]]
@qualifier.push(["map", "{ |x| #{t.to_ruby} }"])
self
end

View file

@ -14,7 +14,8 @@ module Inspec
end
def to_ruby
return rb_skip if !skip.nil?
return rb_skip unless skip.nil?
rb_describe
end
@ -74,7 +75,7 @@ module Inspec
" " + expectation.inspect
end
format("%s%sdescribe %s do\n %s { should%s %s%s }\nend",
only_if_clause, vars, res, itsy, naughty, matcher, xpect)
only_if_clause, vars, res, itsy, naughty, matcher, xpect)
end
def rb_skip

View file

@ -17,23 +17,27 @@ module Inspec
module ResourceDSL
def name(name = nil)
return if name.nil?
@name = name
__register(name, self)
end
def desc(description = nil)
return if description.nil?
__resource_registry[@name].desc(description)
end
def supports(criteria = nil)
return if criteria.nil?
Inspec::Resource.supports[@name] ||= []
Inspec::Resource.supports[@name].push(criteria)
end
def example(example = nil)
return if example.nil?
__resource_registry[@name].example(example)
end
@ -100,17 +104,20 @@ module Inspec
# The new platform resources have methods generated on the fly
# for inspec check to work we need to skip these train errors
raise unless test_backend && e.receiver.class == Train::Transports::Mock::Connection
skip_resource(e.message)
end
end
def self.desc(description = nil)
return @description if description.nil?
@description = description
end
def self.example(example = nil)
return @example if example.nil?
@example = example
end

View file

@ -32,9 +32,9 @@ module Inspec
# traverse out of inspec-vX.Y.Z/lib/inspec/plugins.rb
@home = home || File.join(Inspec.config_dir, "plugins")
@paths += Dir[File.join(@home, "**{,/*/**}", "*.gemspec")]
.map { |x| File.dirname(x) }
.map { |x| Dir[File.join(x, "lib", "inspec-*.rb")] }
.flatten
.map { |x| File.dirname(x) }
.map { |x| Dir[File.join(x, "lib", "inspec-*.rb")] }
.flatten
# load bundled plugins
bundled_dir = File.expand_path(File.dirname(__FILE__))
@ -51,6 +51,7 @@ module Inspec
if path.nil?
raise "Couldn't find plugin #{name}. Searching in #{@home}"
end
# puts "Loading plugin #{name} from #{path}"
require path
end

View file

@ -24,8 +24,8 @@ class PluginRegistry
# @return [Array[Plugin]] sorted list of plugins
def modules
@registry.values
.sort_by { |x| x.respond_to?(:priority) ? x.priority : 0 }
.reverse
.sort_by { |x| x.respond_to?(:priority) ? x.priority : 0 }
.reverse
end
end
@ -44,6 +44,7 @@ class PluginRegistry
# @return [nil] disregard
def self.name(name)
raise "Trying to register #{self} with name == nil" if name.nil?
@name = name
plugin_registry.registry[name] = self
end

View file

@ -40,6 +40,7 @@ module Inspec
end
return Inspec::Plugin::V2::PluginBase if plugin_type.nil?
Inspec::Plugin::V2::PluginBase.base_class_for_type(plugin_type)
end
end

View file

@ -15,12 +15,14 @@ module Inspec::Plugin::V2
def activated?(new_value = nil)
return self[:activated?] if new_value.nil?
self[:activated?] = new_value
end
# Load a plugin, but if an error is encountered, store it and continue
def activate
return if activated?
# rubocop: disable Lint/RescueException
begin
impl_class = self[:activation_proc].call

View file

@ -57,6 +57,7 @@ module Inspec::Plugin::V2
unless existing_entry?(name)
raise Inspec::Plugin::V2::ConfigError, "No such entry with plugin name '#{name}'"
end
@data[:plugins].delete_if { |entry| entry[:name] == name.to_sym }
end
@ -114,6 +115,7 @@ module Inspec::Plugin::V2
next if idx == other_idx
next unless other_entry.is_a? Hash # We'll catch that invalid entry later
next if plugin_entry[:name] != other_entry[:name]
indices = [idx, other_idx].sort
raise Inspec::Plugin::V2::ConfigError, "Malformed plugins.json file - duplicate plugin entry '#{plugin_entry[:name]}' detected at index #{indices[0]} and #{indices[1]}"
end
@ -134,9 +136,10 @@ module Inspec::Plugin::V2
if plugin_entry.key? :installation_type
seen_type = plugin_entry[:installation_type]
unless [:gem, :path].include? seen_type.to_sym
unless %i{gem path}.include? seen_type.to_sym
raise Inspec::Plugin::V2::ConfigError, "'plugins' entry with unrecognized installation_type (must be one of 'gem' or 'path')"
end
plugin_entry[:installation_type] = seen_type.to_sym
if plugin_entry[:installation_type] == :path && !plugin_entry.key?(:installation_path)

View file

@ -46,6 +46,7 @@ module Inspec::Plugin::V2
unless @filter_data.key?("exclude") && @filter_data["exclude"].is_a?(Array)
raise Inspec::Plugin::V2::ConfigError, 'Unknown plugin fillter file format: expected "exclude" to be an array'
end
@filter_data["exclude"].each_with_index do |entry, idx|
unless entry.is_a? Hash
raise Inspec::Plugin::V2::ConfigError, "Unknown plugin fillter file format: expected entry #{idx} to be a Hash / JS Object"

View file

@ -249,7 +249,7 @@ module Inspec::Plugin::V2
end
opts[:scope] ||= :released
unless [:prerelease, :released, :latest].include?(opts[:scope])
unless %i{prerelease released latest}.include?(opts[:scope])
raise SearchError, "Search scope for listing versons must be :prerelease, :released, or :latest."
end
end
@ -267,11 +267,11 @@ module Inspec::Plugin::V2
plugin_local_source = Gem::Source::SpecificFile.new(opts[:gem_file])
plugin_dependency = Gem::Dependency.new(requested_plugin_name,
plugin_local_source.spec.version)
plugin_local_source.spec.version)
requested_local_gem_set = Gem::Resolver::InstallerSet.new(:both)
requested_local_gem_set.add_local(plugin_dependency.name,
plugin_local_source.spec, plugin_local_source)
plugin_local_source.spec, plugin_local_source)
install_gem_to_plugins_dir(plugin_dependency, [requested_local_gem_set])
end
@ -283,8 +283,8 @@ module Inspec::Plugin::V2
end
def install_gem_to_plugins_dir(new_plugin_dependency, # rubocop: disable Metrics/AbcSize
extra_request_sets = [],
update_mode = false)
extra_request_sets = [],
update_mode = false)
# Get a list of all the gems available to us.
gem_to_force_update = update_mode ? new_plugin_dependency.name : nil
@ -305,6 +305,7 @@ module Inspec::Plugin::V2
# Activate all current plugins before trying to activate the new one
loader.list_managed_gems.each do |spec|
next if spec.name == new_plugin_dependency.name && update_mode
spec.activate
end
@ -378,7 +379,7 @@ module Inspec::Plugin::V2
# Find out which gems we still actually need...
names_of_gems_we_actually_need = \
request_set_we_still_must_satisfy.resolve(build_gem_request_universe)
.map(&:full_spec).map(&:full_name)
.map(&:full_spec).map(&:full_name)
# ... vs what we currently have, which should have some cruft
cruft_gem_specs = loader.list_managed_gems.reject do |spec|
@ -423,7 +424,7 @@ module Inspec::Plugin::V2
# find all gem specification directories
directories = [Gem::Specification.default_specifications_dir]
if !defined?(::Bundler)
unless defined?(::Bundler)
# add in any others that do not start with the user directory
directories += Gem::Specification.dirs.find_all do |path|
!path.start_with?(Gem.user_dir)
@ -456,6 +457,7 @@ module Inspec::Plugin::V2
installed_plugins_gem_set = Gem::Resolver::VendorSet.new
loader.list_managed_gems.each do |spec|
next if spec.name == gem_to_force_update
installed_plugins_gem_set.add_vendor_gem(spec.name, spec.gem_dir)
end

View file

@ -168,6 +168,7 @@ module Inspec::Plugin::V2
end
solution.each do |activation_request|
next if activation_request.full_spec.activated?
activation_request.full_spec.activate
# TODO: If we are under Bundler, inform it that we loaded a gem
end
@ -177,6 +178,7 @@ module Inspec::Plugin::V2
status = registry[plugin_name]
return if status.api_generation == 2 # Gen2 have self-annotating superclasses
return if status.api_generation == :'train-1' # Train plugins are here as a courtesy, don't poke them
case status.installation_type
when :bundle
annotate_bundle_plugin_status_after_load(plugin_name)

View file

@ -82,6 +82,7 @@ module Inspec::Plugin::V2
# If called from a Plugin definition class...
stat = reg.find_status_by_class(self)
return stat.name if stat
# Called from an implementation class
return find_name_by_implementation_class(self)
end

View file

@ -32,8 +32,8 @@ module Inspec::Plugin::V2::PluginType
def self.register_with_thor
# Figure out my activator name (= subcommand group name)
subcommand_name = Inspec::Plugin::V2::Registry.instance \
.find_activators(plugin_type: :cli_command, implementation_class: self) \
.first.activator_name.to_s
.find_activators(plugin_type: :cli_command, implementation_class: self) \
.first.activator_name.to_s
# Register with Thor
Inspec::InspecCLI.register(self, subcommand_name, @usage_msg, @desc_msg, {})

View file

@ -30,6 +30,7 @@ module Inspec::Plugin::V2
# HACK: Status is normally the source of truth for loadedness, unless it is a train plugin; then the Train::Registry is the source of truth.
# Also, InSpec registry is keyed on Symbols; Train is keyed on Strings.
return registry.dig(name.to_sym, :loaded) unless name.to_s.start_with?("train-")
Train::Plugins.registry.key?(name.to_s.sub(/^train-/, ""))
end
@ -61,7 +62,7 @@ module Inspec::Plugin::V2
# @returns [Array] Possibly empty array of Activators
def find_activators(filters = {})
plugin_statuses.map(&:activators).flatten.select do |act|
[:plugin_name, :plugin_type, :activator_name, :implementation_class].all? do |criteria|
%i{plugin_name plugin_type activator_name implementation_class}.all? do |criteria|
!filters.key?(criteria) || act[criteria] == filters[criteria]
end
end
@ -75,6 +76,7 @@ module Inspec::Plugin::V2
elsif matched_plugins.empty?
raise Inspec::Plugin::V2::LoadError, "Plugin hooks search returned zero results for filter #{filters.inspect}"
end
matched_plugins.first
end

View file

@ -34,6 +34,7 @@ module Inspec
keys = content.keys
keys.each do |key|
next if content[key].nil?
# remove prefix
rel = Pathname.new(key).relative_path_from(Pathname.new("vendor")).to_s
tar = Pathname.new(opts[:vendor_cache].path).join(rel)
@ -187,10 +188,12 @@ module Inspec
def collect_tests(include_list = @controls)
unless @tests_collected
return unless supports_platform?
locked_dependencies.each(&:collect_tests)
tests.each do |path, content|
next if content.nil? || content.empty?
abs_path = source_reader.target.abs_path(path)
@runner_context.load_control_file(content, abs_path, nil)
end
@ -207,6 +210,7 @@ module Inspec
next if inclusion.is_a?(Regexp)
# Insist the user wrap the regex in slashes to demarcate it as a regex
next unless inclusion.start_with?("/") && inclusion.end_with?("/")
inclusion = inclusion[1..-2] # Trim slashes
begin
re = Regexp.new(inclusion)
@ -271,6 +275,7 @@ module Inspec
# add information about the controls
res[:controls] = res[:controls].map do |id, rule|
next if id.to_s.empty?
data = rule.dup
data.delete(:checks)
data[:impact] ||= 0.5
@ -284,7 +289,7 @@ module Inspec
profile = dep.profile
code = Inspec::MethodSource.code_at(data[:source_location], profile.source_reader)
data[:code] = code unless code.nil? || code.empty?
break if !data[:code].empty?
break unless data[:code].empty?
end
end
data
@ -377,8 +382,8 @@ module Inspec
# only run the vendor check if the legacy profile-path is not used as argument
if @legacy_profile_path == false
# verify that a lockfile is present if we have dependencies
if !metadata.dependencies.empty?
error.call(meta_path, 0, 0, nil, "Your profile needs to be vendored with `inspec vendor`.") if !lockfile_exists?
unless metadata.dependencies.empty?
error.call(meta_path, 0, 0, nil, "Your profile needs to be vendored with `inspec vendor`.") unless lockfile_exists?
end
if lockfile_exists?
@ -393,7 +398,7 @@ module Inspec
next if dep[:name].nil?
# TODO: should we also verify that the soure is the same?
if !lockfile.deps.map { |x| x[:name] }.include? dep[:name]
unless lockfile.deps.map { |x| x[:name] }.include? dep[:name]
error.call(meta_path, 0, 0, nil, "Cannot find #{dep[:name]} in lockfile. Please re-vendor with `inspec vendor`.")
end
end
@ -417,6 +422,7 @@ module Inspec
sline = control[:source_location][:line]
error.call(sfile, sline, nil, id, "Avoid controls with empty IDs") if id.nil? || id.empty?
next if id.start_with? "(generated "
warn.call(sfile, sline, nil, id, "Control #{id} has no title") if control[:title].to_s.empty?
warn.call(sfile, sline, nil, id, "Control #{id} has no descriptions") if control[:descriptions][:default].to_s.empty?
warn.call(sfile, sline, nil, id, "Control #{id} has impact > 1.0") if control[:impact].to_f > 1.0
@ -547,7 +553,7 @@ module Inspec
[["inspec.lock.deps", YAML.dump(deps)]]
files.sort_by { |a| a[0] }
.map { |f| res << f[0] << "\0" << f[1] << "\0" }
.map { |f| res << f[0] << "\0" << f[1] << "\0" }
res.digest.unpack("H*")[0]
end
@ -591,6 +597,7 @@ module Inspec
prefix = @source_reader.target.prefix || ""
tests&.each do |rule|
next if rule.nil?
f = load_rule_filepath(prefix, rule)
load_rule(rule, f, controls, groups)
end
@ -623,7 +630,7 @@ module Inspec
if controls[id][:code].empty? && Inspec::Rule.merge_count(rule) > 0
Inspec::Rule.merge_changes(rule).each do |merge_location|
code = Inspec::MethodSource.code_at(merge_location, source_reader)
if !code.empty?
unless code.empty?
controls[id][:code] = code
break
end

View file

@ -94,7 +94,7 @@ module Inspec
def subcontext_by_name(name)
found = @lib_subcontexts.find { |c| c.profile_id == name }
if !found
unless found
@lib_subcontexts.each do |c|
found = c.subcontext_by_name(name)
break if found
@ -133,6 +133,7 @@ module Inspec
# load all files directly that are flat inside the libraries folder
autoloads.each do |path|
next unless path.end_with?(".rb")
load_library_file(*@require_loader.load(path)) unless @require_loader.loaded?(path)
end
reload_dsl
@ -150,7 +151,7 @@ module Inspec
end
def load_with_context(context, content, source = nil, line = nil)
Inspec::Log.debug("Loading #{source || '<anonymous content>'} into #{self}")
Inspec::Log.debug("Loading #{source || "<anonymous content>"} into #{self}")
@current_load = { file: source }
if content.is_a? Proc
context.instance_eval(&content)
@ -195,6 +196,7 @@ module Inspec
def full_id(pid, rid)
return rid.to_s if pid.to_s.empty?
pid.to_s + "/" + rid.to_s
end
end

View file

@ -54,8 +54,8 @@ module Inspec::Reporters
print_anonymous_control_results(profile)
if @control_count == 0
output(format_message(
indentation: 5,
message: "No tests executed."
indentation: 5,
message: "No tests executed."
))
end
end
@ -86,6 +86,7 @@ module Inspec::Reporters
standard_controls_from_profile(profile).each do |control_from_profile|
control = Control.new(control_from_profile)
next if control.results.nil?
output(format_control_header(control))
control.results.each do |result|
output(format_result(control, result, :standard))
@ -99,6 +100,7 @@ module Inspec::Reporters
anonymous_controls_from_profile(profile).each do |control_from_profile|
control = Control.new(control_from_profile)
next if control.results.nil?
output(format_control_header(control))
control.results.each do |result|
output(format_result(control, result, :anonymous))
@ -111,7 +113,7 @@ module Inspec::Reporters
if profile[:title].nil?
(profile[:name] || "unknown").to_s
else
"#{profile[:title]} (#{profile[:name] || 'unknown'})"
"#{profile[:title]} (#{profile[:name] || "unknown"})"
end
end
@ -163,7 +165,7 @@ module Inspec::Reporters
return text if defined?(RSpec.configuration) && !RSpec.configuration.color
return text unless COLORS.key?(color_name)
"#{COLORS[color_name]}#{text}#{COLORS['reset']}"
"#{COLORS[color_name]}#{text}#{COLORS["reset"]}"
end
def all_unique_controls
@ -182,6 +184,7 @@ module Inspec::Reporters
all_unique_controls.each do |control|
next if control[:id].start_with? "(generated from "
next unless control[:results]
if control[:results].any? { |r| r[:status] == "failed" }
failed += 1
elsif control[:results].any? { |r| r[:status] == "skipped" }
@ -209,6 +212,7 @@ module Inspec::Reporters
all_unique_controls.each do |control|
next unless control[:results]
control[:results].each do |result|
if result[:status] == "failed"
failed += 1
@ -232,9 +236,9 @@ module Inspec::Reporters
summary = profile_summary
return unless summary["total"] > 0
success_str = summary["passed"] == 1 ? "1 successful control" : "#{summary['passed']} successful controls"
failed_str = summary["failed"] == 1 ? "1 control failure" : "#{summary['failed']} control failures"
skipped_str = summary["skipped"] == 1 ? "1 control skipped" : "#{summary['skipped']} controls skipped"
success_str = summary["passed"] == 1 ? "1 successful control" : "#{summary["passed"]} successful controls"
failed_str = summary["failed"] == 1 ? "1 control failure" : "#{summary["failed"]} control failures"
skipped_str = summary["skipped"] == 1 ? "1 control skipped" : "#{summary["skipped"]} controls skipped"
success_color = summary["passed"] > 0 ? "passed" : "no_color"
failed_color = summary["failed"] > 0 ? "failed" : "no_color"
@ -252,7 +256,7 @@ module Inspec::Reporters
def print_tests_summary
summary = tests_summary
failed_str = summary["failed"] == 1 ? "1 failure" : "#{summary['failed']} failures"
failed_str = summary["failed"] == 1 ? "1 failure" : "#{summary["failed"]} failures"
success_color = summary["passed"] > 0 ? "passed" : "no_color"
failed_color = summary["failed"] > 0 ? "failed" : "no_color"
@ -260,9 +264,9 @@ module Inspec::Reporters
s = format(
"Test Summary: %s, %s, %s",
format_with_color(success_color, "#{summary['passed']} successful"),
format_with_color(success_color, "#{summary["passed"]} successful"),
format_with_color(failed_color, failed_str),
format_with_color(skipped_color, "#{summary['skipped']} skipped")
format_with_color(skipped_color, "#{summary["skipped"]} skipped")
)
output(s)

View file

@ -120,6 +120,7 @@ module Inspec::Reporters
def convert_descriptions(data)
return [] if data.nil?
results = []
data.each do |label, text|
results.push({ label: label.to_s, data: text })

View file

@ -36,6 +36,7 @@ module Inspec::Reporters
def merge_profiles
@profiles.each do |profile|
next unless profile.key?(:parent_profile)
parent_profile = find_master_parent(profile)
merge_controls(parent_profile, profile)
merge_depends(parent_profile, profile)
@ -62,6 +63,7 @@ module Inspec::Reporters
control.each do |name, _value|
child_value = child_control[name]
next if child_value.nil? || (child_value.respond_to?(:empty?) && child_value.empty?)
control[name] = child_value
end
end
@ -69,6 +71,7 @@ module Inspec::Reporters
def merge_depends(parent, child)
return unless child.key?(:depends)
child[:depends].each do |d|
parent[:depends] << d
end

View file

@ -17,9 +17,11 @@ module Inspec::Reporters
run_data[:profiles].each do |profile|
profile_id = profile[:name]
next unless profile[:controls]
profile[:controls].each do |control|
control_id = control[:id]
next unless control[:results]
control[:results].each do |result|
result_for_report = {
id: control_id,

View file

@ -41,6 +41,7 @@ module Inspec
end
raise ProfileNotFound, "Cannot find profile named: #{profile_name}" if inner_context.nil?
inner_context.resource_registry[resource_name]
end
@ -51,6 +52,7 @@ module Inspec
# confirm backend custom resources have access to other custom resources
next if backend.respond_to?(id)
backend.class.send(:define_method, id.to_sym) do |*args|
r.new(backend, id.to_s, *args)
end

View file

@ -44,7 +44,7 @@ module Inspec::Resources
filter = FilterTable.create
filter.register_column(:selection_lines, field: "selection_line")
.register_column(:rules, field: "rules")
.register_column(:rules, field: "rules")
filter.install_filter_methods_on_resource(self, :params)
@ -52,6 +52,7 @@ module Inspec::Resources
def read_content
return @content unless @content.nil?
@rules = {}
raw_conf = read_file_content(@conf_path)
@ -74,7 +75,7 @@ module Inspec::Resources
params = []
content.each do |line|
param = parse_line(line)
if !param["selection_line"].nil?
unless param["selection_line"].nil?
params.push(param)
end
end
@ -116,7 +117,7 @@ module Inspec::Resources
rule_list.each_index do |i|
hash_list = @rules[rule_list[i]]
# Cases where rule respresents one or more other rules
if !hash_list.nil?
unless hash_list.nil?
rule_list[i] = hash_list
end
rule_list[i] = handle_multi_rule(rule_list, i)

View file

@ -53,7 +53,7 @@ module Inspec::Resources
def filter_comments(data)
content = ""
data.each_line do |line|
if !line.match(/^\s*#/)
unless line.match(/^\s*#/)
content << line
end
end

View file

@ -55,6 +55,7 @@ module Inspec::Resources
def enabled?
return false if find_repo.count == 0
actives = find_repo.map { |repo| repo[:active] }
actives = actives.uniq
actives.size == 1 && actives[0] = true
@ -113,6 +114,7 @@ module Inspec::Resources
def determine_ppa_url(ppa_url)
# verify if we have the url already, then just return
return ppa_url if ppa_url =~ HTTP_URL_RE
# otherwise start generating the ppa url
# special care if the name stats with :

View file

@ -30,7 +30,7 @@ module Inspec::Resources
def initialize
unless inspec.command("/sbin/auditctl").exist?
raise Inspec::Exceptions::ResourceFailed,
"Command `/sbin/auditctl` does not exist"
"Command `/sbin/auditctl` does not exist"
end
auditctl_cmd = "/sbin/auditctl -l"
@ -38,7 +38,7 @@ module Inspec::Resources
if result.exit_status != 0
raise Inspec::Exceptions::ResourceFailed,
"Command `#{auditctl_cmd}` failed with error: #{result.stderr}"
"Command `#{auditctl_cmd}` failed with error: #{result.stderr}"
end
@content = result.stdout
@ -46,24 +46,24 @@ module Inspec::Resources
if @content =~ /^LIST_RULES:/
raise Inspec::Exceptions::RsourceFailed,
"The version of audit is outdated." \
"The `auditd` resource supports versions of audit >= 2.3."
"The version of audit is outdated." \
"The `auditd` resource supports versions of audit >= 2.3."
end
parse_content
end
filter = FilterTable.create
filter.register_column(:file, field: "file")
.register_column(:list, field: "list")
.register_column(:action, field: "action")
.register_column(:fields, field: "fields")
.register_column(:fields_nokey, field: "fields_nokey")
.register_column(:syscall, field: "syscall")
.register_column(:key, field: "key")
.register_column(:arch, field: "arch")
.register_column(:path, field: "path")
.register_column(:permissions, field: "permissions")
.register_column(:exit, field: "exit")
filter.register_column(:file, field: "file")
.register_column(:list, field: "list")
.register_column(:action, field: "action")
.register_column(:fields, field: "fields")
.register_column(:fields_nokey, field: "fields_nokey")
.register_column(:syscall, field: "syscall")
.register_column(:key, field: "key")
.register_column(:arch, field: "arch")
.register_column(:path, field: "path")
.register_column(:permissions, field: "permissions")
.register_column(:exit, field: "exit")
filter.install_filter_methods_on_resource(self, :params)
@ -73,13 +73,14 @@ module Inspec::Resources
# See: https://github.com/inspec/inspec/issues/3113
if @status_content =~ /^AUDIT_STATUS/
@status_content = @status_content.gsub("AUDIT_STATUS: ", "")
.tr(" ", "\n")
.tr("=", " ")
.tr(" ", "\n")
.tr("=", " ")
end
@status_params ||= Hash[@status_content.scan(/^([^ ]+) (.*)$/)]
return @status_params[name] if name
@status_params
end

View file

@ -37,6 +37,7 @@ module Inspec::Resources
def has_interface?(interface)
return skip_resource "The `bridge` resource does not provide interface detection for Windows yet" if inspec.os.windows?
bridge_info.nil? ? false : bridge_info[:interfaces].include?(interface)
end
@ -52,7 +53,8 @@ module Inspec::Resources
def bridge_info
return @cache if defined?(@cache)
@cache = @bridge_provider.bridge_info(@bridge_name) if !@bridge_provider.nil?
@cache = @bridge_provider.bridge_info(@bridge_name) unless @bridge_provider.nil?
end
end
@ -102,7 +104,7 @@ module Inspec::Resources
end
# ensure we have an array of groups
bridges = [bridges] if !bridges.is_a?(Array)
bridges = [bridges] unless bridges.is_a?(Array)
# select the requested interface
bridges = bridges.each_with_object([]) do |adapter, adapter_collection|
@ -115,6 +117,7 @@ module Inspec::Resources
end
return nil if bridges.empty?
warn "[Possible Error] detected multiple bridges interfaces with the name #{bridge_name}" if bridges.size > 1
bridges[0]
end

View file

@ -20,6 +20,7 @@ module Inspec::Resources
def initialize(package_name, _opts = {})
raise "Chocolatey is not installed" unless inspec.command("choco").exist?
@package_name = package_name
@cache = base_data.update(generate_cache)
end
@ -67,6 +68,7 @@ module Inspec::Resources
cmd = inspec.powershell(command.strip)
return {} if cmd.exit_status != 0 || cmd.stdout.strip.empty?
out = JSON.parse(cmd.stdout)
{

View file

@ -35,7 +35,7 @@ module Inspec::Resources
# Make sure command is replaced so sensitive output isn't shown
@command = "ERROR"
raise Inspec::Exceptions::ResourceFailed,
"The `redact_regex` option must be a regular expression"
"The `redact_regex` option must be a regular expression"
end
@redact_regex = options[:redact_regex]
end

View file

@ -50,7 +50,8 @@ module Inspec::Resources
def read_crontab
if is_system_crontab?
raise Inspec::Exceptions::ResourceFailed, "Supplied crontab path '#{@path}' must exist!" if !inspec.file(@path).exist?
raise Inspec::Exceptions::ResourceFailed, "Supplied crontab path '#{@path}' must exist!" unless inspec.file(@path).exist?
ct = inspec.file(@path).content
else
ct = inspec.command(crontab_cmd).stdout
@ -70,13 +71,13 @@ module Inspec::Resources
end
filter = FilterTable.create
filter.register_column(:minutes, field: "minute")
.register_column(:hours, field: "hour")
.register_column(:days, field: "day")
.register_column(:months, field: "month")
.register_column(:weekdays, field: "weekday")
.register_column(:user, field: "user")
.register_column(:commands, field: "command")
filter.register_column(:minutes, field: "minute")
.register_column(:hours, field: "hour")
.register_column(:days, field: "day")
.register_column(:months, field: "month")
.register_column(:weekdays, field: "weekday")
.register_column(:user, field: "user")
.register_column(:commands, field: "command")
# rebuild the crontab line from raw content
filter.register_custom_property(:content) do |t, _|

View file

@ -28,7 +28,7 @@ module Inspec::Resources
end
# implicit conversion of values
csv = CSV.new(content, headers: true, converters: [:all, :blank_to_nil])
csv = CSV.new(content, headers: true, converters: %i{all blank_to_nil})
# convert to hash
csv.to_a.map(&:to_hash)

View file

@ -36,36 +36,42 @@ class DhParams < Inspec.resource(1)
# its('generator') { should eq 2 }
def generator
return if @dh_params.nil?
@dh_params.g.to_i
end
# its('modulus') { should eq '00:91:a0:15:89:e5:bc:38:93:12:02:fc:...' }
def modulus
return if @dh_params.nil?
"00:" + @dh_params.p.to_s(16).downcase.scan(/.{2}/).join(":")
end
# its('pem') { should eq '-----BEGIN DH PARAMETERS...' }
def pem
return if @dh_params.nil?
@dh_params.to_pem
end
# its('prime_length') { should be 2048 }
def prime_length
return if @dh_params.nil?
@dh_params.p.num_bits
end
# its('text') { should eq 'human-readable-text' }
def text
return if @dh_params.nil?
@dh_params.to_text
end
# it { should be_valid }
def valid?
return if @dh_params.nil?
@dh_params.params_ok?
end

View file

@ -11,21 +11,21 @@ module Inspec::Resources
# use filtertable for containers
filter = FilterTable.create
filter.register_custom_matcher(:exists?) { |x| !x.entries.empty? }
filter.register_column(:commands, field: "command")
.register_column(:ids, field: "id")
.register_column(:images, field: "image")
.register_column(:labels, field: "labels", style: :simple)
.register_column(:local_volumes, field: "localvolumes")
.register_column(:mounts, field: "mounts")
.register_column(:names, field: "names")
.register_column(:networks, field: "networks")
.register_column(:ports, field: "ports")
.register_column(:running_for, field: "runningfor")
.register_column(:sizes, field: "size")
.register_column(:status, field: "status")
.register_custom_matcher(:running?) do |x|
x.where { status.downcase.start_with?("up") }
end
filter.register_column(:commands, field: "command")
.register_column(:ids, field: "id")
.register_column(:images, field: "image")
.register_column(:labels, field: "labels", style: :simple)
.register_column(:local_volumes, field: "localvolumes")
.register_column(:mounts, field: "mounts")
.register_column(:names, field: "names")
.register_column(:networks, field: "networks")
.register_column(:ports, field: "ports")
.register_column(:running_for, field: "runningfor")
.register_column(:sizes, field: "size")
.register_column(:status, field: "status")
.register_custom_matcher(:running?) do |x|
x.where { status.downcase.start_with?("up") }
end
filter.install_filter_methods_on_resource(self, :containers)
attr_reader :containers
@ -37,13 +37,13 @@ module Inspec::Resources
class DockerImageFilter
filter = FilterTable.create
filter.register_custom_matcher(:exists?) { |x| !x.entries.empty? }
filter.register_column(:ids, field: "id")
.register_column(:repositories, field: "repository")
.register_column(:tags, field: "tag")
.register_column(:sizes, field: "size")
.register_column(:digests, field: "digest")
.register_column(:created, field: "createdat")
.register_column(:created_since, field: "createdsize")
filter.register_column(:ids, field: "id")
.register_column(:repositories, field: "repository")
.register_column(:tags, field: "tag")
.register_column(:sizes, field: "size")
.register_column(:digests, field: "digest")
.register_column(:created, field: "createdat")
.register_column(:created_since, field: "createdsize")
filter.install_filter_methods_on_resource(self, :images)
attr_reader :images
@ -54,10 +54,10 @@ module Inspec::Resources
class DockerPluginFilter
filter = FilterTable.create
filter.add(:ids, field: "id")
.add(:names, field: "name")
.add(:versions, field: "version")
.add(:enabled, field: "enabled")
filter.add(:ids, field: "id")
.add(:names, field: "name")
.add(:versions, field: "version")
.add(:enabled, field: "enabled")
filter.connect(self, :plugins)
attr_reader :plugins
@ -69,12 +69,12 @@ module Inspec::Resources
class DockerServiceFilter
filter = FilterTable.create
filter.register_custom_matcher(:exists?) { |x| !x.entries.empty? }
filter.register_column(:ids, field: "id")
.register_column(:names, field: "name")
.register_column(:modes, field: "mode")
.register_column(:replicas, field: "replicas")
.register_column(:images, field: "image")
.register_column(:ports, field: "ports")
filter.register_column(:ids, field: "id")
.register_column(:names, field: "name")
.register_column(:modes, field: "mode")
.register_column(:replicas, field: "replicas")
.register_column(:images, field: "image")
.register_column(:ports, field: "ports")
filter.install_filter_methods_on_resource(self, :services)
attr_reader :services
@ -147,6 +147,7 @@ module Inspec::Resources
def version
return @version if defined?(@version)
data = {}
cmd = inspec.command("docker version --format '{{ json . }}'")
data = JSON.parse(cmd.stdout) if cmd.exit_status == 0
@ -157,6 +158,7 @@ module Inspec::Resources
def info
return @info if defined?(@info)
data = {}
# docke info format is only supported for Docker 17.03+
cmd = inspec.command("docker info --format '{{ json . }}'")
@ -169,6 +171,7 @@ module Inspec::Resources
# returns information about docker objects
def object(id)
return @inspect if defined?(@inspect)
data = JSON.parse(inspec.command("docker inspect #{id}").stdout)
data = data[0] if data.is_a?(Array)
@inspect = Hashie::Mash.new(data)
@ -185,7 +188,7 @@ module Inspec::Resources
def parse_json_command(labels, subcommand)
# build command
format = labels.map { |label| "\"#{label}\": {{json .#{label}}}" }
raw = inspec.command("docker #{subcommand} --format '{#{format.join(', ')}}'").stdout
raw = inspec.command("docker #{subcommand} --format '{#{format.join(", ")}}'").stdout
output = []
# since docker is not outputting valid json, we need to parse each row
raw.each_line do |entry|
@ -238,7 +241,7 @@ module Inspec::Resources
def ensure_keys(entry, labels)
labels.each do |key|
entry[key.downcase] = nil if !entry.key?(key.downcase)
entry[key.downcase] = nil unless entry.key?(key.downcase)
end
entry
end

View file

@ -83,6 +83,7 @@ module Inspec::Resources
def object_info
return @info if defined?(@info)
opts = @opts
@info = inspec.docker.containers.where { names == opts[:name] || (!id.nil? && !opts[:id].nil? && (id == opts[:id] || id.start_with?(opts[:id]))) }
end

View file

@ -74,6 +74,7 @@ module Inspec::Resources
def object_info
return @info if defined?(@info)
opts = @opts
@info = inspec.docker.images.where do
(repository == opts[:repo] && tag == opts[:tag]) || (!id.nil? && !opts[:id].nil? && (id == opts[:id] || id.start_with?(opts[:id])))

View file

@ -54,6 +54,7 @@ module Inspec::Resources
def object_info
return @info if defined?(@info)
opts = @opts
@info = inspec.docker.plugins.where do
(name == opts[:name]) || (!id.nil? && !opts[:id].nil? && (id == opts[:id]))

View file

@ -81,6 +81,7 @@ module Inspec::Resources
def object_info
return @info if defined?(@info)
opts = @opts
@info = inspec.docker.services.where do
name == opts[:name] || image == opts[:image] || (!id.nil? && !opts[:id].nil? && (id == opts[:id] || id.start_with?(opts[:id])))

View file

@ -24,29 +24,29 @@ module Inspec::Resources
filter = FilterTable.create
filter.register_custom_matcher(:exists?) { |x| !x.entries.empty? }
filter.register_column(:cluster_name, field: "cluster_name")
.register_column(:node_name, field: "name")
.register_column(:transport_address, field: "transport_address")
.register_column(:host, field: "host")
.register_column(:ip, field: "ip")
.register_column(:version, field: "version")
.register_column(:build_hash, field: "build_hash")
.register_column(:total_indexing_buffer, field: "total_indexing_buffer")
.register_column(:roles, field: "roles")
.register_column(:settings, field: "settings")
.register_column(:os, field: "os")
.register_column(:process, field: "process")
.register_column(:jvm, field: "jvm")
.register_column(:transport, field: "transport")
.register_column(:http, field: "http")
.register_column(:plugins, field: "plugins")
.register_column(:plugin_list, field: "plugin_list")
.register_column(:modules, field: "modules")
.register_column(:module_list, field: "module_list")
.register_column(:node_id, field: "node_id")
.register_column(:ingest, field: "ingest")
.register_custom_property(:node_count) do |t, _|
t.entries.length
end
.register_column(:node_name, field: "name")
.register_column(:transport_address, field: "transport_address")
.register_column(:host, field: "host")
.register_column(:ip, field: "ip")
.register_column(:version, field: "version")
.register_column(:build_hash, field: "build_hash")
.register_column(:total_indexing_buffer, field: "total_indexing_buffer")
.register_column(:roles, field: "roles")
.register_column(:settings, field: "settings")
.register_column(:os, field: "os")
.register_column(:process, field: "process")
.register_column(:jvm, field: "jvm")
.register_column(:transport, field: "transport")
.register_column(:http, field: "http")
.register_column(:plugins, field: "plugins")
.register_column(:plugin_list, field: "plugin_list")
.register_column(:modules, field: "modules")
.register_column(:module_list, field: "module_list")
.register_column(:node_id, field: "node_id")
.register_column(:ingest, field: "ingest")
.register_custom_property(:node_count) do |t, _|
t.entries.length
end
filter.install_filter_methods_on_resource(self, :nodes)
@ -156,7 +156,7 @@ module Inspec::Resources
def verify_json_payload!(content)
unless content["error"].nil?
raise "#{content['error']['type']}: #{content['error']['reason']}"
raise "#{content["error"]["type"]}: #{content["error"]["reason"]}"
end
raise "No successful nodes available in cluster" if content["_nodes"]["successful"] == 0

View file

@ -37,13 +37,13 @@ module Inspec::Resources
end
filter = FilterTable.create
filter.register_column(:device_name, field: "device_name")
.register_column(:mount_point, field: "mount_point")
.register_column(:file_system_type, field: "file_system_type")
.register_column(:mount_options, field: "mount_options")
.register_column(:dump_options, field: "dump_options")
.register_column(:file_system_options, field: "file_system_options")
.register_custom_matcher(:configured?) { |x| x.entries.any? }
filter.register_column(:device_name, field: "device_name")
.register_column(:mount_point, field: "mount_point")
.register_column(:file_system_type, field: "file_system_type")
.register_column(:mount_options, field: "mount_options")
.register_column(:dump_options, field: "dump_options")
.register_column(:file_system_options, field: "file_system_options")
.register_custom_matcher(:configured?) { |x| x.entries.any? }
filter.install_filter_methods_on_resource(self, :params)
@ -53,6 +53,7 @@ module Inspec::Resources
def home_mount_options
return nil unless where { mount_point == "/home" }.configured?
where { mount_point == "/home" }.entries[0].mount_options
end

View file

@ -56,6 +56,7 @@ module Inspec::Resources
def users(filter = nil)
entries = filter || @entries
return nil if entries.nil?
# filter the user entry
res = entries.map do |x|
x["members"].split(",") if !x.nil? && !x["members"].nil?
@ -66,6 +67,7 @@ module Inspec::Resources
def where(conditions = {})
return if conditions.empty?
fields = {
name: "name",
group_name: "name",
@ -81,6 +83,7 @@ module Inspec::Resources
conditions.each do |k, v|
idx = fields[k.to_sym]
next if idx.nil?
res = res.select { |x| x[idx].to_s == v.to_s }
end
end
@ -113,6 +116,7 @@ module Inspec::Resources
x = line.split(":")
# abort if we have an empty or comment line
return nil if x.empty?
# map data
{
"name" => x.at(0), # Name of the group.

View file

@ -31,10 +31,10 @@ class EtcHosts < Inspec.resource(1)
end
FilterTable.create
.register_column(:ip_address, field: "ip_address")
.register_column(:primary_name, field: "primary_name")
.register_column(:all_host_names, field: "all_host_names")
.install_filter_methods_on_resource(self, :params)
.register_column(:ip_address, field: "ip_address")
.register_column(:primary_name, field: "primary_name")
.register_column(:all_host_names, field: "all_host_names")
.install_filter_methods_on_resource(self, :params)
private

View file

@ -27,9 +27,9 @@ module Inspec::Resources
end
filter = FilterTable.create
filter.register_column(:daemon, field: "daemon")
.register_column(:client_list, field: "client_list")
.register_column(:options, field: "options")
filter.register_column(:daemon, field: "daemon")
.register_column(:client_list, field: "client_list")
.register_column(:options, field: "options")
filter.install_filter_methods_on_resource(self, :params)
@ -47,6 +47,7 @@ module Inspec::Resources
content.each do |line|
data, = parse_comment_line(line, comment_char: "#", standalone_comments: false)
next unless data != ""
data.split(":")[0].split(",").each do |daemon|
split_daemons_list.push("#{daemon} : " + line.split(":", 2)[1])
end
@ -98,6 +99,7 @@ module Inspec::Resources
def initialize(path = nil)
return skip_resource "`etc_hosts_deny` is not supported on your OS" unless inspec.os.linux?
super(path || "/etc/hosts.deny")
end

View file

@ -57,6 +57,7 @@ module Inspec::Resources
def content
res = file.content
return nil if res.nil?
res.force_encoding("utf-8")
end
@ -102,7 +103,7 @@ module Inspec::Resources
Inspec.deprecate(:file_resource_be_mounted_matchers, "The file resource `be_mounted.with` and `be_mounted.only_with` matchers are deprecated. Please use the `mount` resource instead")
# we cannot read mount data on non-Linux systems
return nil if !inspec.os.linux?
return nil unless inspec.os.linux?
# parse content if we are on linux
@mount_options ||= parse_mount_options(mounted.stdout, true)
@ -171,6 +172,7 @@ module Inspec::Resources
def file_permission_granted?(access_type, by_usergroup, by_specific_user)
raise "`file_permission_granted?` is not supported on your OS" if @perms_provider.nil?
if by_specific_user.nil? || by_specific_user.empty?
@perms_provider.check_file_permission_by_mask(file, access_type, by_usergroup, by_specific_user)
else
@ -215,6 +217,7 @@ module Inspec::Resources
flag = permission_flag(access_type)
mask = file.unix_mode_mask(usergroup, flag)
raise "Invalid usergroup/owner provided" if mask.nil?
(file.mode & mask) != 0
end

View file

@ -39,8 +39,9 @@ module Inspec::Resources
end
def info
return @cache if !@cache.nil?
return @cache unless @cache.nil?
return {} if @fsman.nil?
@cache = @fsman.info(@partition)
end
@ -119,12 +120,13 @@ module Inspec::Resources
EOF
raise Inspec::Exceptions::ResourceSkipped, "Unable to get available space for partition #{partition}" if cmd.stdout == "" || cmd.exit_status.to_i != 0
begin
fs = JSON.parse(cmd.stdout)
rescue JSON::ParserError => e
raise Inspec::Exceptions::ResourceFailed,
"Failed to parse JSON from Powershell. " \
"Error: #{e}"
"Failed to parse JSON from Powershell. " \
"Error: #{e}"
end
{
name: fs["DeviceID"],

View file

@ -28,10 +28,10 @@ module Inspec::Resources
attr_reader :params
filter = FilterTable.create
filter.register_column(:zone, field: "zone")
.register_column(:interfaces, field: "interfaces")
.register_column(:sources, field: "sources")
.register_column(:services, field: "services")
filter.register_column(:zone, field: "zone")
.register_column(:interfaces, field: "interfaces")
.register_column(:sources, field: "sources")
.register_column(:services, field: "services")
filter.install_filter_methods_on_resource(self, :params)
@ -45,12 +45,14 @@ module Inspec::Resources
def has_zone?(query_zone)
return false unless installed?
result = firewalld_command("--get-zones").split(" ")
result.include?(query_zone)
end
def running?
return false unless installed?
result = firewalld_command("--state")
result =~ /^running/ ? true : false
end
@ -135,6 +137,7 @@ module Inspec::Resources
if result.stderr != ""
return "Error on command #{command}: #{result.stderr}"
end
result.stdout.strip
end
end

View file

@ -49,10 +49,10 @@ module Inspec::Resources
filter = FilterTable.create
filter.register_custom_matcher(:exists?) { |x| !x.entries.empty? }
filter.register_column(:names, field: "name")
.register_column(:gids, field: "gid")
.register_column(:domains, field: "domain")
.register_column(:members, field: "members", style: :simple)
filter.register_column(:names, field: "name")
.register_column(:gids, field: "gid")
.register_column(:domains, field: "domain")
.register_column(:members, field: "members", style: :simple)
filter.install_filter_methods_on_resource(self, :collect_group_details)
def to_s
@ -64,6 +64,7 @@ module Inspec::Resources
# collects information about every group
def collect_group_details
return @groups_cache ||= @group_provider.groups unless @group_provider.nil?
[]
end
end
@ -176,6 +177,7 @@ module Inspec::Resources
groups.each { |g| g["gid"] = g["gid"].to_i }
groups.each do |g|
next if g["users"].nil?
g["members"] = g.delete("users")
g["members"].tr!(" ", ",")
end

View file

@ -90,6 +90,7 @@ class GrubConfig < Inspec.resource(1)
lines = content.split("\n")
lines.each_with_index do |line, index|
next unless line =~ /^menuentry\s+.*/
entry = {}
entry["insmod"] = []
@ -104,6 +105,7 @@ class GrubConfig < Inspec.resource(1)
# Begin processing from index forward until a `}` line is met
lines.drop(index + 1).each do |mline|
break if mline =~ /^\s*}\s*$/
case mline
when /(?:^|\s*)initrd.*/
entry["initrd"] = mline.split(" ")[1]
@ -155,6 +157,7 @@ class GrubConfig < Inspec.resource(1)
kernel_opts = {}
lines.each_with_index do |file_line, index|
next unless file_line =~ /^title.*/
current_kernel = file_line.split(" ", 2)[1]
lines.drop(index + 1).each do |kernel_line|
if kernel_line =~ /^\s.*/

View file

@ -72,7 +72,7 @@ module Inspec::Resources
missing_requirements = @host_provider.missing_requirements(protocol)
unless missing_requirements.empty?
return skip_resource "The following requirements are not met for this resource: " \
"#{missing_requirements.join(', ')}"
"#{missing_requirements.join(", ")}"
end
end
@ -83,7 +83,7 @@ module Inspec::Resources
# if we get the IP address, the host is resolvable
def resolvable?(type = nil)
warn "The `host` resource ignores #{type} parameters. Continue to resolve host." if !type.nil?
warn "The `host` resource ignores #{type} parameters. Continue to resolve host." unless type.nil?
resolve.nil? || resolve.empty? ? false : true
end
@ -131,7 +131,8 @@ module Inspec::Resources
def resolve
return @ip_cache if defined?(@ip_cache)
@ip_cache = @host_provider.resolve(hostname) if !@host_provider.nil?
@ip_cache = @host_provider.resolve(hostname) unless @host_provider.nil?
end
end
@ -248,6 +249,7 @@ module Inspec::Resources
cmd.stdout.lines.each do |line|
ip, = line.split(/\s+/, 2)
next unless ip.match(Resolv::IPv4::Regex) || ip.match(Resolv::IPv6::Regex)
addresses << ip unless addresses.include?(ip)
end

View file

@ -35,8 +35,8 @@ module Inspec::Resources
# profiles.
if opts.key?(:enable_remote_worker) && !inspec.local_transport?
warn "Ignoring `enable_remote_worker` option, the `http` resource ",
"remote worker is enabled by default for remote targets and ",
"cannot be disabled"
"remote worker is enabled by default for remote targets and ",
"cannot be disabled"
end
# Run locally if InSpec is ran locally and remotely if ran remotely
@ -138,6 +138,7 @@ module Inspec::Resources
def response
return @response if @response
conn = Faraday.new(url: url, headers: request_headers, params: params, ssl: { verify: ssl_verify? }) do |builder|
builder.request :url_encoded
builder.use FaradayMiddleware::FollowRedirects, limit: max_redirects if max_redirects > 0
@ -163,7 +164,7 @@ module Inspec::Resources
def initialize(inspec, http_method, url, opts)
unless inspec.command("curl").exist?
raise Inspec::Exceptions::ResourceSkipped,
"curl is not available on the target machine"
"curl is not available on the target machine"
end
@ran_curl = false
@ -203,6 +204,7 @@ module Inspec::Resources
prelude, remainder = response.split("\n\n", 2)
loop do
break unless remainder =~ %r{^HTTP/}
prelude, remainder = remainder.split("\n\n", 2)
end
@body = remainder
@ -248,7 +250,7 @@ module Inspec::Resources
if params.nil?
cmd << "'#{url}'"
else
cmd << "'#{url}?#{params.map { |e| e.join('=') }.join('&')}'"
cmd << "'#{url}?#{params.map { |e| e.join("=") }.join("&")}'"
end
cmd.join(" ")

View file

@ -76,6 +76,7 @@ module Inspec::Resources
def iis_app
return @cache unless @cache.nil?
command = "Import-Module WebAdministration; Get-WebApplication -Name '#{@path}' -Site '#{@site_name}' | Select-Object * | ConvertTo-Json"
cmd = @inspec.command(command)

View file

@ -117,7 +117,7 @@ class IisAppPool < Inspec.resource(1)
e32b: pool["enable32BitAppOnWin64"],
mode: pool["managedPipelineMode"],
processes: process_model["maxProcesses"],
timeout: "#{idle_timeout['Hours']}:#{idle_timeout['Minutes']}:#{idle_timeout['Seconds']}",
timeout: "#{idle_timeout["Hours"]}:#{idle_timeout["Minutes"]}:#{idle_timeout["Seconds"]}",
timeout_days: idle_timeout["Days"],
timeout_hours: idle_timeout["Hours"],
timeout_minutes: idle_timeout["Minutes"],

View file

@ -82,8 +82,9 @@ module Inspec::Resources
end
def iis_site
return @cache if !@cache.nil?
@cache = @site_provider.iis_site(@site_name) if !@site_provider.nil?
return @cache unless @cache.nil?
@cache = @site_provider.iis_site(@site_name) unless @site_provider.nil?
end
end
@ -106,7 +107,7 @@ module Inspec::Resources
end
bindings_array = site["bindings"]["Collection"].map do |k|
"#{k['protocol']} #{k['bindingInformation']}#{k['protocol'] == 'https' ? " sslFlags=#{k['sslFlags']}" : ''}"
"#{k["protocol"]} #{k["bindingInformation"]}#{k["protocol"] == "https" ? " sslFlags=#{k["sslFlags"]}" : ""}"
end
# map our values to a hash table

View file

@ -61,13 +61,13 @@ module Inspec::Resources
def ipv4_addresses_netmask
ipv4_cidrs.map { |i| i.split("/") }.map do |addr, netlen|
binmask = "#{'1' * netlen.to_i}#{'0' * (32 - netlen.to_i)}".to_i(2)
binmask = "#{"1" * netlen.to_i}#{"0" * (32 - netlen.to_i)}".to_i(2)
netmask = []
(1..4).each do |_byte|
netmask.unshift(binmask & 255)
binmask = binmask >> 8
end
"#{addr}/#{netmask.join('.')}"
"#{addr}/#{netmask.join(".")}"
end
end
@ -87,7 +87,8 @@ module Inspec::Resources
def interface_info
return @cache if defined?(@cache)
@cache = @interface_provider.interface_info(@iface) if !@interface_provider.nil?
@cache = @interface_provider.interface_info(@iface) unless @interface_provider.nil?
end
end
@ -142,6 +143,7 @@ module Inspec::Resources
[4, 6].each do |v|
cmd = inspec.command("/sbin/ip -br -#{v} address show dev #{iface}")
next unless cmd.exit_status.to_i == 0
family = v == 6 ? "inet6" : "inet"
cmd.stdout.each_line do |line|
@ -171,8 +173,8 @@ module Inspec::Resources
end
# ensure we have an array of groups
net_adapter = [net_adapter] if !net_adapter.is_a?(Array)
addresses = [addresses] if !addresses.is_a?(Array)
net_adapter = [net_adapter] unless net_adapter.is_a?(Array)
addresses = [addresses] unless addresses.is_a?(Array)
# select the requested interface
adapters = net_adapter.each_with_object([]) do |adapter, adapter_collection|
@ -188,6 +190,7 @@ module Inspec::Resources
end
return nil if adapters.empty?
warn "[Possible Error] detected multiple network interfaces with the name #{iface}" if adapters.size > 1
adapters[0]
end
@ -196,8 +199,8 @@ module Inspec::Resources
def addresses_for_proto(all_addresses, iface, proto)
all_addresses.select { |i| i["InterfaceAlias"] == iface }
.map { |i| "#{i["#{proto}Address"]}/#{i['PrefixLength']}" unless i["#{proto}Address"].nil? }
.compact
.map { |i| "#{i["#{proto}Address"]}/#{i["PrefixLength"]}" unless i["#{proto}Address"].nil? }
.compact
end
end
end

View file

@ -59,7 +59,7 @@ module Inspec::Resources
end
def to_s
"#{resource_base_name} #{@resource_name_supplement || 'content'}"
"#{resource_base_name} #{@resource_name_supplement || "content"}"
end
private

View file

@ -36,7 +36,7 @@ module Inspec::Resources
def initialize(modulename = nil)
@module = modulename
# this resource is only supported on Linux
return skip_resource "The `kernel_parameter` resource is not supported on your OS." if !inspec.os.linux?
return skip_resource "The `kernel_parameter` resource is not supported on your OS." unless inspec.os.linux?
end
def loaded?

View file

@ -15,12 +15,13 @@ module Inspec::Resources
@parameter = parameter
# this resource is only supported on Linux
return skip_resource "The `kernel_parameter` resource is not supported on your OS." if !inspec.os.linux?
return skip_resource "The `kernel_parameter` resource is not supported on your OS." unless inspec.os.linux?
end
def value
cmd = inspec.command("/sbin/sysctl -q -n #{@parameter}")
return nil if cmd.exit_status != 0
# remove whitespace
cmd = cmd.stdout.chomp.strip
# convert to number if possible

View file

@ -31,26 +31,31 @@ module Inspec::Resources
def public?
return if @key.nil?
@key.public?
end
def public_key
return if @key.nil?
@key.public_key.to_s
end
def private?
return if @key.nil?
@key.private?
end
def private_key
return if @key.nil?
@key.to_s
end
def key_length
return if @key.nil?
@key.public_key.n.num_bytes * 8
end

View file

@ -21,6 +21,7 @@ module Inspec::Resources
@path = path
@mount_manager = mount_manager_for_os
return skip_resource "The `mount` resource is not supported on your OS yet." if @mount_manager.nil?
@file = inspec.backend.file(@path)
end
@ -31,11 +32,12 @@ module Inspec::Resources
def count
mounted = file.mounted
return nil if mounted.nil? || mounted.stdout.nil?
mounted.stdout.lines.count
end
def method_missing(name)
return nil if !file.mounted?
return nil unless file.mounted?
mounted = file.mounted
return nil if mounted.nil? || mounted.stdout.nil?

View file

@ -17,11 +17,12 @@ module Inspec::Resources
k = name.to_s
res = @params[k]
return true if res.nil? && @params.key?(k)
@params[k]
end
def to_s
"MySQL Config entry [#{@path.join(' ')}]"
"MySQL Config entry [#{@path.join(" ")}]"
end
end
@ -112,6 +113,7 @@ module Inspec::Resources
def abs_path(dir, f)
return f if f.start_with? "/"
File.join(dir, f)
end

View file

@ -73,12 +73,14 @@ module Inspec::Resources
def init_fallback
# support debian mysql administration login
return if inspec.platform.in_family?("windows")
debian = inspec.command("test -f /etc/mysql/debian.cnf && cat /etc/mysql/debian.cnf").stdout
return if debian.empty?
user = debian.match(/^\s*user\s*=\s*([^ ]*)\s*$/)
pass = debian.match(/^\s*password\s*=\s*([^ ]*)\s*$/)
return if user.nil? || pass.nil?
@user = user[1]
@pass = pass[1]
end

View file

@ -28,6 +28,7 @@ module Inspec::Resources
if cmd.exit_status != 0
return skip_resource "Error using the command nginx -V"
end
@data = cmd.stdout
@params = {}
read_content

View file

@ -33,6 +33,7 @@ module Inspec::Resources
@conf_path = conf_path || "/etc/nginx/nginx.conf"
@contents = {}
return skip_resource "The `nginx_conf` resource is currently not supported on Windows." if inspec.os.windows?
read_content(@conf_path)
end
@ -57,11 +58,13 @@ module Inspec::Resources
def read_content(path)
return @contents[path] if @contents.key?(path)
@contents[path] = read_file_content(path, allow_empty: true)
end
def parse_nginx(path)
return nil if inspec.os.windows?
content = read_content(path)
# Don't attempt to parse file if it contains only comments or is empty
@ -96,10 +99,10 @@ module Inspec::Resources
# into the current data structure
if data.key?("include")
data.delete("include").flatten
.map { |x| File.expand_path(x, rel_path) }
.map { |x| find_files(x) }.flatten
.map { |path| parse_nginx(path) }
.each { |conf| merge_config!(data, conf) }
.map { |x| File.expand_path(x, rel_path) }
.map { |x| find_files(x) }.flatten
.map { |path| parse_nginx(path) }
.each { |conf| merge_config!(data, conf) }
end
# Walk through the remaining hash fields to find more references
@ -114,6 +117,7 @@ module Inspec::Resources
def merge_config!(data, conf)
# Catch edge-cases
return if data.nil? || conf.nil?
# Step through all conf items and create combined return value
data.merge!(conf) do |_, v1, v2|
if v1.is_a?(Array) && v2.is_a?(Array)
@ -160,7 +164,7 @@ module Inspec::Resources
filter = FilterTable.create
filter.register_column(:servers, field: "server")
.install_filter_methods_on_resource(self, :server_table)
.install_filter_methods_on_resource(self, :server_table)
def locations
servers.map(&:locations).flatten
@ -187,7 +191,7 @@ module Inspec::Resources
filter = FilterTable.create
filter.register_column(:locations, field: "location")
.install_filter_methods_on_resource(self, :location_table)
.install_filter_methods_on_resource(self, :location_table)
def to_s
server = ""

View file

@ -26,6 +26,7 @@ module Inspec::Resources
param = read_params[name.to_s]
# extract first value if we have only one value in array
return param[0] if param.is_a?(Array) && (param.length == 1)
param
end

View file

@ -23,7 +23,7 @@ module Inspec::Resources
@package_name = package_name
# verify that this resource is only supported on Windows
return skip_resource "The `oneget` resource is not supported on your OS." if !inspec.os.windows?
return skip_resource "The `oneget` resource is not supported on your OS." unless inspec.os.windows?
end
def info

View file

@ -36,6 +36,7 @@ module Inspec::Resources
# connection as sysdba stuff
return skip_resource "Option 'as_os_user' not available in Windows" if inspec.os.windows? && opts[:as_os_user]
@su_user = opts[:as_os_user]
@db_role = opts[:as_db_role]
@ -93,7 +94,7 @@ module Inspec::Resources
def verify_query(query)
# ensure we have a ; at the end
query + ";" if !query.strip.end_with?(";")
query + ";" unless query.strip.end_with?(";")
query
end
@ -121,7 +122,7 @@ module Inspec::Resources
doc = REXML::Document.new result
table = doc.elements["table"]
hash = []
if !table.nil?
unless table.nil?
rows = table.elements.to_a
headers = rows[0].elements.to_a("th").map { |entry| entry.text.strip }
rows.delete_at(0)
@ -134,6 +135,7 @@ module Inspec::Resources
entries = row.elements.to_a("td")
# ignore if we have empty entries, oracle is adding th rows in between
return nil if entries.empty?
headers.each_with_index do |header, index|
# we need htmlentities since we do not have nokogiri
coder = HTMLEntities.new

View file

@ -43,6 +43,7 @@ module Inspec::Resources
def content
return @content if defined?(@content)
@content = value_for(@osenv, @target) unless @osenv.nil?
end

View file

@ -65,11 +65,12 @@ module Inspec::Resources
# returns the package description
def info
return @cache if !@cache.nil?
return @cache unless @cache.nil?
# All `@pkgman.info` methods return `{}`. This matches that
# behavior if `@pkgman` can't be determined, thus avoiding the
# `undefined method 'info' for nil:NilClass` error
return {} if @pkgman.nil?
@pkgman.info(@package_name)
end
@ -88,6 +89,7 @@ module Inspec::Resources
def evaluate_missing_requirements
missing_requirements_string = @pkgman.missing_requirements.uniq.join(", ")
return if missing_requirements_string.empty?
raise Inspec::Exceptions::ResourceSkipped, "The following requirements are not met for this resource: #{missing_requirements_string}"
end
end
@ -154,6 +156,7 @@ module Inspec::Resources
# CentOS does not return an error code if the package is not installed,
# therefore we need to check for emptyness
return {} if cmd.exit_status.to_i != 0 || cmd.stdout.chomp.empty?
params = SimpleConfig.new(
cmd.stdout.chomp,
assignment_regex: /^\s*([^:]*?)\s*:\s*(.*?)\s*$/,
@ -214,8 +217,8 @@ module Inspec::Resources
}
rescue JSON::ParserError => e
raise Inspec::Exceptions::ResourceFailed,
"Failed to parse JSON from `brew` command. " \
"Error: #{e}"
"Failed to parse JSON from `brew` command. " \
"Error: #{e}"
end
end
@ -244,6 +247,7 @@ module Inspec::Resources
def info(package_name)
cmd = inspec.command("swlist -l product | grep #{package_name}")
return {} if cmd.exit_status.to_i != 0
pkg = cmd.stdout.strip.split(" ")
{
name: pkg[0],
@ -303,8 +307,8 @@ module Inspec::Resources
package = JSON.parse(cmd.stdout)
rescue JSON::ParserError => e
raise Inspec::Exceptions::ResourceFailed,
"Failed to parse JSON from PowerShell. " \
"Error: #{e}"
"Failed to parse JSON from PowerShell. " \
"Error: #{e}"
end
# What if we match multiple packages? just pick the first one for now.
@ -381,7 +385,7 @@ module Inspec::Resources
name: params["Name"],
installed: true,
# 0.5.11-0.175.3.1.0.5.0
version: "#{params['Version']}-#{params['Branch']}",
version: "#{params["Version"]}-#{params["Branch"]}",
type: "pkg",
}
end

View file

@ -42,11 +42,11 @@ module Inspec::Resources
end
filter = FilterTable.create
filter.register_column(:statuses, field: "status", style: :simple)
.register_column(:names, field: "name")
.register_column(:versions, field: "version")
.register_column(:architectures, field: "architecture")
.install_filter_methods_on_resource(self, :filtered_packages)
filter.register_column(:statuses, field: "status", style: :simple)
.register_column(:names, field: "name")
.register_column(:versions, field: "version")
.register_column(:architectures, field: "architecture")
.install_filter_methods_on_resource(self, :filtered_packages)
private
@ -82,6 +82,7 @@ module Inspec::Resources
cmd = inspec.command(command)
all = cmd.stdout.split("\n")
return [] if all.nil?
all.map do |m|
a = m.split(/ {2,}/)
a[0] = "installed" if a[0] =~ /^.i/
@ -99,6 +100,7 @@ module Inspec::Resources
cmd = inspec.command(command)
all = cmd.stdout.split("\n")
return [] if all.nil?
all.map do |m|
a = m.split(" ")
a.unshift("installed")

Some files were not shown because too many files have changed in this diff Show more