Bump Rubocop to 0.49.1 (#2323)

* Bump Rubocop to 0.49.1

This change bumps Rubocop to 0.49.1. There have been a lot of changes
since 0.39.0 and this PR is hopefully a nice compromise of turning off
certain cops and updating our codebase to take advantage of new Ruby
2.3 methods and operators.

Signed-off-by: Adam Leff <adam@leff.co>

* Set end-of-line format to line-feed only, avoid Windows-related CRLF issues

Signed-off-by: Adam Leff <adam@leff.co>
This commit is contained in:
Adam Leff 2017-11-21 02:49:41 -05:00 committed by Christoph Hartmann
parent b9b502a48d
commit 4b9acb4800
64 changed files with 437 additions and 460 deletions

View file

@ -8,30 +8,72 @@ AllCops:
- 'examples/**/*'
- 'vendor/**/*'
- 'lib/bundles/inspec-init/templates/**/*'
Documentation:
Enabled: false
- 'www/tutorial/**/*'
AlignParameters:
Enabled: true
Encoding:
Enabled: true
BlockDelimiters:
Enabled: false
Documentation:
Enabled: false
EmptyLinesAroundBlockBody:
Enabled: false
FrozenStringLiteralComment:
Enabled: false
HashSyntax:
Enabled: true
LineLength:
Enabled: false
EmptyLinesAroundBlockBody:
Layout/AlignHash:
Enabled: false
Layout/EmptyLineAfterMagicComment:
Enabled: false
Layout/EndOfLine:
Enabled: true
EnforcedStyle: lf
Layout/SpaceAroundOperators:
Enabled: false
MethodLength:
Max: 40
NumericLiterals:
MinDigits: 10
Metrics/AbcSize:
Max: 33
Metrics/BlockLength:
Max: 50
Metrics/CyclomaticComplexity:
Max: 10
Metrics/PerceivedComplexity:
Max: 11
Metrics/AbcSize:
Max: 33
NumericLiterals:
MinDigits: 10
Security/YAMLLoad:
Enabled: false
Style/AndOr:
Enabled: false
Style/BracesAroundHashParameters:
Enabled: false
Style/ClassAndModuleChildren:
Enabled: false
Style/ConditionalAssignment:
Enabled: false
Style/EmptyMethod:
Enabled: false
Style/Encoding:
Enabled: false
Style/FileName:
Enabled: false
Style/IfUnlessModifier:
Enabled: false
Style/MethodMissing:
Enabled: false
Style/MultilineIfModifier:
Enabled: false
Style/NegatedIf:
Enabled: false
Style/Not:
Enabled: false
Style/NumericLiteralPrefix:
Enabled: false
Style/NumericPredicate:
Enabled: false
Style/PercentLiteralDelimiters:
PreferredDelimiters:
'%': '{}'
@ -43,33 +85,13 @@ Style/PercentLiteralDelimiters:
'%w': '{}'
'%W': ()
'%x': ()
Style/AlignHash:
Enabled: false
Style/PredicateName:
Enabled: false
Style/ClassAndModuleChildren:
Style/SymbolArray:
Enabled: false
Style/ConditionalAssignment:
Enabled: false
Style/BracesAroundHashParameters:
Enabled: false
Style/AndOr:
Enabled: false
Style/Not:
Enabled: false
Style/FileName:
Enabled: false
Style/TrailingCommaInLiteral:
EnforcedStyleForMultiline: comma
Style/TrailingCommaInArguments:
EnforcedStyleForMultiline: comma
Style/NegatedIf:
Enabled: false
Style/TrailingCommaInLiteral:
EnforcedStyleForMultiline: comma
Style/UnlessElse:
Enabled: false
BlockDelimiters:
Enabled: false
Style/SpaceAroundOperators:
Enabled: false
Style/IfUnlessModifier:
Enabled: false

View file

@ -13,7 +13,7 @@ group :test do
gem 'bundler', '~> 1.5'
gem 'minitest', '~> 5.5'
gem 'rake', '~> 10'
gem 'rubocop', '= 0.39.0'
gem 'rubocop', '= 0.49.1'
gem 'simplecov', '~> 0.10'
gem 'concurrent-ruby', '~> 0.9'
gem 'mocha', '~> 1.1'

View file

@ -20,7 +20,7 @@ Gem::Specification.new do |spec|
'{bin,docs,examples,lib}/**/*', File::FNM_DOTMATCH
).reject { |f| File.directory?(f) }
spec.executables = %w{ inspec }
spec.executables = %w{inspec}
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']

View file

@ -211,17 +211,12 @@ module Artifact
def valid_header?(file_alg, file_version, file_keyname)
public_keyfile = "#{file_keyname}.pem.pub"
puts "Looking for #{public_keyfile} to verify artifact"
if not File.exist? public_keyfile
if !File.exist? public_keyfile
raise "Can't find #{public_keyfile}"
end
if not VALID_PROFILE_DIGESTS.member? file_alg
raise 'Invalid artifact digest algorithm detected'
end
if not VALID_PROFILE_VERSIONS.member? file_version
raise 'Invalid artifact version detected'
end
raise 'Invalid artifact digest algorithm detected' if !VALID_PROFILE_DIGESTS.member?(file_alg)
raise 'Invalid artifact version detected' if !VALID_PROFILE_VERSIONS.member?(file_version)
end
def verify(file_to_verifiy, &content_block)

View file

@ -79,11 +79,11 @@ module Compliance
# exit 1 if the version of compliance that we're working with doesn't support odic
def legacy_check!(feature)
if !supported?(feature)
puts "This feature (#{feature}) is not available for legacy installations."
puts 'Please upgrade to a recent version of Chef Compliance.'
exit 1
end
return if supported?(feature)
puts "This feature (#{feature}) is not available for legacy installations."
puts 'Please upgrade to a recent version of Chef Compliance.'
exit 1
end
private

View file

@ -12,10 +12,8 @@ module Compliance
def self.get(url, headers = nil, insecure)
uri = _parse_url(url)
req = Net::HTTP::Get.new(uri.path)
if !headers.nil?
headers.each do |key, value|
req.add_field(key, value)
end
headers&.each do |key, value|
req.add_field(key, value)
end
send_request(uri, req, insecure)
end
@ -72,7 +70,6 @@ module Compliance
http.request(req)
}
res
rescue OpenSSL::SSL::SSLError => e
raise e unless e.message.include? 'certificate verify failed'

View file

@ -37,15 +37,15 @@ module Compliance
server = 'compliance'
msg = "inspec compliance login https://your_compliance_server --user admin --insecure --token 'PASTE TOKEN HERE' "
end
raise Inspec::FetcherFailure, <<EOF
raise Inspec::FetcherFailure, <<~EOF
Cannot fetch #{uri} because your #{server} token has not been
configured.
Cannot fetch #{uri} because your #{server} token has not been
configured.
Please login using
Please login using
#{msg}
EOF
#{msg}
EOF
end
# verifies that the target e.g base/ssh exists

View file

@ -13,7 +13,7 @@ puts "Run test as #{user} in path #{pwd}"
access_token = ENV['COMPLIANCE_ACCESSTOKEN']
refresh_token = ENV['COMPLIANCE_REFRESHTOKEN']
%w{refresh_token access_token}.each do |type|
%w{refresh_token access_token}.each do |type| # rubocop:disable Metrics/BlockLength
case type
when 'access_token'
token_options = "--token '#{access_token}'"

View file

@ -136,27 +136,21 @@ module Habitat
Habitat::Log.info('Checking to see if Habitat is installed...')
cmd = Mixlib::ShellOut.new('hab --version')
cmd.run_command
if cmd.error?
exit_with_error('Unable to run Habitat commands.', cmd.stderr)
end
exit_with_error('Unable to run Habitat commands.', cmd.stderr) if cmd.error?
end
def validate_habitat_origin
if habitat_origin.nil?
exit_with_error(
'Unable to determine Habitat origin name.',
'Run `hab setup` or set the HAB_ORIGIN environment variable.',
)
end
exit_with_error(
'Unable to determine Habitat origin name.',
'Run `hab setup` or set the HAB_ORIGIN environment variable.',
) if habitat_origin.nil?
end
def validate_habitat_auth_token
if habitat_auth_token.nil?
exit_with_error(
'Unable to determine Habitat auth token for publishing.',
'Run `hab setup` or set the HAB_AUTH_TOKEN environment variable.',
)
end
exit_with_error(
'Unable to determine Habitat auth token for publishing.',
'Run `hab setup` or set the HAB_AUTH_TOKEN environment variable.',
) if habitat_auth_token.nil?
end
def validate_output_dir
@ -318,78 +312,78 @@ module Habitat
end
def plan_contents
plan = <<-EOL
pkg_name=#{package_name}
pkg_version=#{profile.version}
pkg_origin=#{habitat_origin}
pkg_deps=(chef/inspec core/ruby core/hab)
pkg_svc_user=root
EOL
plan = <<~EOL
pkg_name=#{package_name}
pkg_version=#{profile.version}
pkg_origin=#{habitat_origin}
pkg_deps=(chef/inspec core/ruby core/hab)
pkg_svc_user=root
EOL
plan += "pkg_license='#{profile.metadata.params[:license]}'\n\n" if profile.metadata.params[:license]
plan += <<-EOL
plan += <<~EOL
do_build() {
cp -vr $PLAN_CONTEXT/../* $HAB_CACHE_SRC_PATH/$pkg_dirname
}
do_build() {
cp -vr $PLAN_CONTEXT/../* $HAB_CACHE_SRC_PATH/$pkg_dirname
}
do_install() {
local profile_contents
local excludes
profile_contents=($(ls))
excludes=(habitat results *.hart)
do_install() {
local profile_contents
local excludes
profile_contents=($(ls))
excludes=(habitat results *.hart)
for item in ${excludes[@]}; do
profile_contents=(${profile_contents[@]/$item/})
done
for item in ${excludes[@]}; do
profile_contents=(${profile_contents[@]/$item/})
done
mkdir ${pkg_prefix}/dist
cp -r ${profile_contents[@]} ${pkg_prefix}/dist/
}
mkdir ${pkg_prefix}/dist
cp -r ${profile_contents[@]} ${pkg_prefix}/dist/
}
EOL
plan
end
def run_hook_contents
<<-EOL
#!/bin/sh
<<~EOL
#!/bin/sh
# redirect stderr to stdout
# ultimately, we'd like to log this somewhere useful, but due to
# https://github.com/habitat-sh/habitat/issues/2395, we need to
# avoid doing that for now.
exec 2>&1
# redirect stderr to stdout
# ultimately, we'd like to log this somewhere useful, but due to
# https://github.com/habitat-sh/habitat/issues/2395, we need to
# avoid doing that for now.
exec 2>&1
# InSpec will try to create a .cache directory in the user's home directory
# so this needs to be someplace writeable by the hab user
export HOME={{pkg.svc_var_path}}
# InSpec will try to create a .cache directory in the user's home directory
# so this needs to be someplace writeable by the hab user
export HOME={{pkg.svc_var_path}}
PROFILE_IDENT="{{pkg.origin}}/{{pkg.name}}"
RESULTS_DIR="{{pkg.svc_var_path}}/inspec_results"
RESULTS_FILE="${RESULTS_DIR}/{{pkg.name}}.json"
PROFILE_IDENT="{{pkg.origin}}/{{pkg.name}}"
RESULTS_DIR="{{pkg.svc_var_path}}/inspec_results"
RESULTS_FILE="${RESULTS_DIR}/{{pkg.name}}.json"
# Create a directory for inspec formatter output
mkdir -p {{pkg.svc_var_path}}/inspec_results
# Create a directory for inspec formatter output
mkdir -p {{pkg.svc_var_path}}/inspec_results
while true; do
echo "Executing InSpec for ${PROFILE_IDENT}"
inspec exec {{pkg.path}}/dist --format=json > ${RESULTS_FILE}
while true; do
echo "Executing InSpec for ${PROFILE_IDENT}"
inspec exec {{pkg.path}}/dist --format=json > ${RESULTS_FILE}
if [ $? -eq 0 ]; then
echo "InSpec run completed successfully."
else
echo "InSpec run did not complete successfully. If you do not see any errors above,"
echo "control failures were detected. Check the InSpec results here for details:"
echo ${RESULTS_FILE}
echo "Otherwise, troubleshoot any errors shown above."
fi
if [ $? -eq 0 ]; then
echo "InSpec run completed successfully."
else
echo "InSpec run did not complete successfully. If you do not see any errors above,"
echo "control failures were detected. Check the InSpec results here for details:"
echo ${RESULTS_FILE}
echo "Otherwise, troubleshoot any errors shown above."
fi
source {{pkg.svc_config_path}}/settings.sh
echo "sleeping for ${SLEEP_TIME} seconds"
sleep ${SLEEP_TIME}
done
source {{pkg.svc_config_path}}/settings.sh
echo "sleeping for ${SLEEP_TIME} seconds"
sleep ${SLEEP_TIME}
done
EOL
end
end

View file

@ -54,11 +54,11 @@ module Supermarket
def self.find(profile, supermarket_url = SUPERMARKET_URL)
profiles = Supermarket::API.profiles(supermarket_url)
if !profiles.empty?
index = profiles.index { |t| same?(profile, t, supermarket_url) }
# return profile or nil
profiles[index] if !index.nil? && index >= 0
end
return if profiles.empty?
index = profiles.index { |t| same?(profile, t, supermarket_url) }
# return profile or nil
profiles[index] if !index.nil? && index >= 0
end
# verifies that a profile exists
@ -75,9 +75,9 @@ module Supermarket
def self.send_request(uri, req)
# send request
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') {|http|
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
http.request(req)
}
end
[res.is_a?(Net::HTTPSuccess), res.body]
end
end

View file

@ -42,7 +42,7 @@ module Supermarket
# check that the profile is available
supermarket_profiles = Supermarket::API.profiles
found = supermarket_profiles.select { |p|
"#{p['tool_owner']}/#{p['slug']}" == profile
profile == "#{p['tool_owner']}/#{p['slug']}"
}
if found.empty?

View file

@ -24,14 +24,12 @@ module Fetchers
# you got to this file during debugging, you may want to look at the
# omnibus source for hints.
#
class Git < Inspec.fetcher(1) # rubocop:disable ClassLength
class Git < Inspec.fetcher(1)
name 'git'
priority 200
def self.resolve(target, opts = {})
if target.respond_to?(:has_key?) &&target.key?(:git)
new(target[:git], opts.merge(target))
end
new(target[:git], opts.merge(target)) if target.respond_to?(:has_key?) && target.key?(:git)
end
def initialize(remote_url, opts = {})
@ -121,10 +119,7 @@ module Fetchers
if tagged_commit
tagged_commit.first
else
found = pairs.find { |m| m[1].end_with?(ref_name.to_s) }
if found
found.first
end
pairs.find { |m| m[1].end_with?(ref_name.to_s) }&.first
end
end

View file

@ -16,19 +16,15 @@ module Fetchers
resolve_from_hash(target)
end
if local_path
new(local_path)
end
new(local_path) if local_path
end
def self.resolve_from_hash(target)
if target.key?(:path)
local_path = target[:path]
if target.key?(:cwd)
local_path = File.expand_path(local_path, target[:cwd])
end
local_path
end
return unless target.key?(:path)
local_path = target[:path]
local_path = File.expand_path(local_path, target[:cwd]) if target.key?(:cwd)
local_path
end
def self.resolve_from_string(target)
@ -40,9 +36,7 @@ module Fetchers
target = target.tr('\\', '/')
end
if File.exist?(target)
target
end
target if File.exist?(target)
end
def initialize(target)

View file

@ -141,7 +141,7 @@ 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 if !@temp_archive_path.nil?
Inspec::Log.debug("Fetching URL: #{@target}")
remote = open(@target, http_opts)
@archive_type = file_type_from_remote(remote) # side effect :(

View file

@ -68,7 +68,6 @@ module Inspec
end
cls.new
rescue Train::ClientError => e
raise "Client error, can't connect to '#{name}' backend: #{e.message}"
rescue Train::TransportError => e

View file

@ -134,7 +134,7 @@ module Inspec
config = File.read(file)
end
JSON.load(config)
JSON.parse(config)
rescue JSON::ParserError => e
puts "Failed to load JSON configuration: #{e}\nConfig was: #{config.inspect}"
exit 1

View file

@ -48,20 +48,19 @@ module Inspec
end
def assert_cache_sanity!
if target.respond_to?(:key?) && target.key?(:sha256)
if fetcher.resolved_source[:sha256] != target[:sha256]
raise <<EOF
The remote source #{fetcher} no longer has the requested content:
return unless target.respond_to?(:key?) && target.key?(:sha256)
Request Content Hash: #{target[:sha256]}
Actual Content Hash: #{fetcher.resolved_source[:sha256]}
exception_message = <<~EOF
The remote source #{fetcher} no longer has the requested content:
For URL, supermarket, compliance, and other sources that do not
provide versioned artifacts, this likely means that the remote source
has changed since your lockfile was generated.
EOF
end
end
Request Content Hash: #{target[:sha256]}
Actual Content Hash: #{fetcher.resolved_source[:sha256]}
For URL, supermarket, compliance, and other sources that do not
provide versioned artifacts, this likely means that the remote source
has changed since your lockfile was generated.
EOF
raise exception_message if fetcher.resolved_source[:sha256] != target[:sha256]
end
end
end

View file

@ -1,4 +1,3 @@
#!/usr/bin/env ruby
# encoding: utf-8
# Copyright 2015 Dominik Richter
# author: Dominik Richter

View file

@ -40,7 +40,7 @@ module Inspec
profile_context_owner = profile_context
profile_id = profile_context.profile_id
Class.new do
Class.new do # rubocop:disable Metrics/BlockLength
include Inspec::DSL
include Inspec::DSL::RequireOverride
include resources_dsl
@ -80,7 +80,7 @@ module Inspec
# the describe block in the context of that control.
#
define_method :describe do |*args, &block|
loc = block_location(block, caller[0])
loc = block_location(block, caller(1..1).first)
id = "(generated from #{loc} #{SecureRandom.hex})"
res = nil

View file

@ -31,22 +31,22 @@ module Inspec
# rubocop:disable Style/GuardClause
def self.validate_lockfile_version!(version)
if version < MINIMUM_SUPPORTED_VERSION
raise <<EOF
This lockfile specifies a lockfile_version of #{version} which is
lower than the minimum supported version #{MINIMUM_SUPPORTED_VERSION}.
raise <<~EOF
This lockfile specifies a lockfile_version of #{version} which is
lower than the minimum supported version #{MINIMUM_SUPPORTED_VERSION}.
Please create a new lockfile for this project by running:
Please create a new lockfile for this project by running:
inspec vendor
EOF
inspec vendor
EOF
elsif version > CURRENT_LOCKFILE_VERSION
raise <<EOF
This lockfile claims to be version #{version} which is greater than
the most recent lockfile version(#{CURRENT_LOCKFILE_VERSION}).
raise <<~EOF
This lockfile claims to be version #{version} which is greater than
the most recent lockfile version(#{CURRENT_LOCKFILE_VERSION}).
This may happen if you are using an older version of inspec than was
used to create the lockfile.
EOF
This may happen if you are using an older version of inspec than was
used to create the lockfile.
EOF
end
end
# rubocop:enable Style/GuardClause
@ -87,9 +87,7 @@ EOF
end
def parse_content_hash_1(lockfile_content_hash)
@deps = if lockfile_content_hash['depends']
lockfile_content_hash['depends'].map { |i| symbolize_keys(i) }
end
@deps = lockfile_content_hash['depends']&.map { |i| symbolize_keys(i) }
end
def mutate_hash_keys_with(hash, fun)

View file

@ -111,7 +111,7 @@ module Inspec
# load the profile for the requirement
def profile
return @profile if ! @profile.nil?
return @profile unless @profile.nil?
opts = @opts.dup
opts[:backend] = @backend
if !@dependencies.nil?

View file

@ -64,11 +64,9 @@ module Inspec
path_string + " -> #{dep.name}"
end
if new_seen_items.key?(dep.resolved_source)
raise Inspec::CyclicDependencyError, "Dependency #{dep} would cause a dependency cycle (#{new_path_string})"
else
new_seen_items[dep.resolved_source] = true
end
raise Inspec::CyclicDependencyError, "Dependency #{dep} would cause a dependency cycle (#{new_path_string})" if new_seen_items.key?(dep.resolved_source)
new_seen_items[dep.resolved_source] = true
if !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}"

View file

@ -33,12 +33,12 @@ module Inspec::DSL
dep_entry = dependencies.list[profile_id]
if dep_entry.nil?
raise <<EOF
Cannot load #{profile_id} since it is not listed as a dependency of #{bind_context.profile_name}.
raise <<~EOF
Cannot load #{profile_id} since it is not listed as a dependency of #{bind_context.profile_name}.
Dependencies available from this context are:
#{dependencies.list.keys.join("\n ")}
EOF
Dependencies available from this context are:
#{dependencies.list.keys.join("\n ")}
EOF
end
context = dep_entry.profile.runner_context

View file

@ -18,7 +18,7 @@ module Inspec
# We cannot rely on libraries residing on disk however.
# TODO: Sandboxing.
content, path, line = @require_loader.load(rbpath)
eval(content, TOPLEVEL_BINDING, path, line) # rubocop:disable Lint/Eval
eval(content, TOPLEVEL_BINDING, path, line) # rubocop:disable Security/Eval
end
end
end

View file

@ -41,7 +41,7 @@ module Inspec
end
def have_shell?
! (@shell.nil? || @shell.empty?)
!(@shell.nil? || @shell.empty?)
end
def have_shell_completion?
@ -61,26 +61,26 @@ module Inspec
end
def print_usage_guidance
puts <<EOF
# To use this, eval it in your shell
#
# #{EVAL_COMMANDS[shell]}
#
#
EOF
puts <<~EOF
# To use this, eval it in your shell
#
# #{EVAL_COMMANDS[shell]}
#
#
EOF
end
def print_detection_warning(device)
device.puts <<EOF
#
# The shell #{@shell} was auto-detected. If this is incorrect, please
# specify a shell explicitly by running:
#
# inspec env SHELLNAME
#
# Currently supported shells are: #{shells_with_completions.join(', ')}
#
EOF
device.puts <<~EOF
#
# The shell #{@shell} was auto-detected. If this is incorrect, please
# specify a shell explicitly by running:
#
# inspec env SHELLNAME
#
# Currently supported shells are: #{shells_with_completions.join(', ')}
#
EOF
end
def exit_no_completion
@ -93,14 +93,14 @@ EOF
if @detected
$stderr.puts '# Unable to automatically detect shell and no shell was provided.'
end
$stderr.puts <<EOF
#
# Please provide the name of your shell via the command line:
#
# inspec env SHELLNAME
#
# Currently supported shells are: #{shells_with_completions.join(', ')}
EOF
$stderr.puts <<~EOF
#
# Please provide the name of your shell via the command line:
#
# inspec env SHELLNAME
#
# Currently supported shells are: #{shells_with_completions.join(', ')}
EOF
exit 1
end

View file

@ -110,7 +110,7 @@ module Inspec
errors = []
warnings = []
%w{ name version }.each do |field|
%w{name version}.each do |field|
next unless params[field.to_sym].nil?
errors.push("Missing profile #{field} in #{ref}")
end
@ -126,7 +126,7 @@ module Inspec
errors.push('Version needs to be in SemVer format')
end
%w{ title summary maintainer copyright license }.each do |field|
%w{title summary maintainer copyright license}.each do |field|
next unless params[field.to_sym].nil?
warnings.push("Missing profile #{field} in #{ref}")
end
@ -165,11 +165,11 @@ module Inspec
return obj.map { |i| symbolize_keys(i) } if obj.is_a?(Array)
return obj unless obj.is_a?(Hash)
obj.each_with_object({}) {|(k, v), h|
obj.each_with_object({}) do |(k, v), h|
v = symbolize_keys(v) if v.is_a?(Hash)
v = symbolize_keys(v) if v.is_a?(Array)
h[k.to_sym] = v
}
end
end
def self.finalize_supports_elem(elem, logger)
@ -188,7 +188,8 @@ module Inspec
logger ||= Logger.new(nil)
logger.warn(
"Do not use deprecated `supports: #{x}` syntax. Instead use:\n"\
"supports:\n - os-family: #{x}\n\n")
"supports:\n - os-family: #{x}\n\n",
)
{ :'os-family' => x } # rubocop:disable Style/HashSyntax
end
end
@ -202,7 +203,8 @@ module Inspec
logger ||= Logger.new(nil)
logger.warn(
"Do not use deprecated `supports: #{x}` syntax. Instead use:\n"\
"supports:\n - os-family: #{x}\n\n")
"supports:\n - os-family: #{x}\n\n",
)
[{ :'os-family' => x }] # rubocop:disable Style/HashSyntax
end
end
@ -223,10 +225,9 @@ module Inspec
# create a new name based on the original target if it exists
# Crudely slug the target to not contain slashes, to avoid breaking
# unit tests that look for warning sequences
unless original_target.to_s.empty?
metadata.params[:title] = "tests from #{original_target}"
metadata.params[:name] = metadata.params[:title].gsub(%r{[\\\/]}, '.')
end
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)

View file

@ -24,10 +24,12 @@ module Inspec
test.negate!
test
}.map(&:to_ruby).join("\n")
return all_tests
all_tests
else
all_tests = @tests.map(&:to_ruby).join("\n").gsub("\n", "\n ")
return format("describe.one do\n %s\nend", all_tests)
format("describe.one do\n %s\nend", all_tests)
end
end

View file

@ -42,7 +42,7 @@ module Inspec
def describe_chain
return nil if @qualifier.empty?
resource = (@qualifier.length > 1) ? @qualifier[0..-2] : [@qualifier[0]]
resource = @qualifier.length > 1 ? @qualifier[0..-2] : [@qualifier[0]]
res = resource.map { |q| ruby_qualifier(q) }.join('.')
xres = nil

View file

@ -106,7 +106,7 @@ module Inspec
# we share the backend between profiles.
#
# This will cause issues if a profile attempts to load a file via `inspec.profile.file`
train_options = options.select { |k, _| k != 'target' } # See https://github.com/chef/inspec/pull/1646
train_options = options.reject { |k, _| k == 'target' } # See https://github.com/chef/inspec/pull/1646
@backend = options[:backend].nil? ? Inspec::Backend.create(train_options) : options[:backend].dup
@runtime_profile = RuntimeProfile.new(self)
@backend.profile = @runtime_profile
@ -421,7 +421,7 @@ module Inspec
[['inspec.yml', source_reader.metadata.content]] +
[['inspec.lock.deps', YAML.dump(deps)]]
files.sort { |a, b| a[0] <=> b[0] }
files.sort_by { |a| a[0] }
.map { |f| res << f[0] << "\0" << f[1] << "\0" }
res.digest.unpack('H*')[0]

View file

@ -66,9 +66,7 @@ module Inspec
end
def self.validate_resource_dsl_version!(version)
if version != 1
raise 'Only resource version 1 is supported!'
end
raise 'Only resource version 1 is supported!' if version != 1
end
end

View file

@ -455,10 +455,10 @@ class InspecRspecCli < InspecRspecJson # rubocop:disable Metrics/ClassLength
end
def print_last_control_with_examples
if @last_control
print_control(@last_control)
@last_control.examples.each { |example| print_result(example) }
end
return unless @last_control
print_control(@last_control)
@last_control.examples.each { |example| print_result(example) }
end
def last_control_is_anonymous?
@ -634,8 +634,7 @@ class InspecRspecCli < InspecRspecJson # rubocop:disable Metrics/ClassLength
s = format('Profile Summary: %s, %s, %s',
format_with_color(success_color, success_str),
format_with_color(failed_color, failed_str),
format_with_color(skipped_color, skipped_str),
)
format_with_color(skipped_color, skipped_str))
output.puts(s) if summary['total'] > 0
end
@ -651,8 +650,7 @@ class InspecRspecCli < InspecRspecJson # rubocop:disable Metrics/ClassLength
s = format('Test Summary: %s, %s, %s',
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.puts(s)
end

View file

@ -103,35 +103,34 @@ module Inspec
def print_target_info
ctx = @runner.backend
puts <<EOF
You are currently running on:
puts <<~EOF
You are currently running on:
OS platform: #{mark ctx.os[:name] || 'unknown'}
OS family: #{mark ctx.os[:family] || 'unknown'}
OS release: #{mark ctx.os[:release] || 'unknown'}
EOF
OS platform: #{mark ctx.os[:name] || 'unknown'}
OS family: #{mark ctx.os[:family] || 'unknown'}
OS release: #{mark ctx.os[:release] || 'unknown'}
EOF
end
def help(topic = nil)
if topic.nil?
puts <<EOF
puts <<~EOF
Available commands:
Available commands:
`[resource]` - run resource on target machine
`help resources` - show all available resources that can be used as commands
`help [resource]` - information about a specific resource
`help matchers` - show information about common matchers
`exit` - exit the InSpec shell
`[resource]` - run resource on target machine
`help resources` - show all available resources that can be used as commands
`help [resource]` - information about a specific resource
`help matchers` - show information about common matchers
`exit` - exit the InSpec shell
You can use resources in this environment to test the target machine. For example:
You can use resources in this environment to test the target machine. For example:
command('uname -a').stdout
file('/proc/cpuinfo').content => "value"
command('uname -a').stdout
file('/proc/cpuinfo').content => "value"
#{print_target_info}
EOF
#{print_target_info}
EOF
elsif topic == 'resources'
resources.sort.each do |resource|
puts " - #{resource}"
@ -164,60 +163,60 @@ EOF
end
def print_matchers_help
puts <<-EOL
Matchers are used to compare resource values to expectations. While some
resources implement their own custom matchers, the following matchers are
common amongst all resources:
puts <<~EOL
Matchers are used to compare resource values to expectations. While some
resources implement their own custom matchers, the following matchers are
common amongst all resources:
#{mark 'be'}
#{mark 'be'}
The #{mark 'be'} matcher can be used to compare numeric values.
The #{mark 'be'} matcher can be used to compare numeric values.
its('size') { should be >= 10 }
its('size') { should be >= 10 }
#{mark 'cmp'}
#{mark 'cmp'}
The #{mark 'cmp'} matcher is like #{mark 'eq'} but less restrictive. It will try
to fit the resource value to the expectation.
The #{mark 'cmp'} matcher is like #{mark 'eq'} but less restrictive. It will try
to fit the resource value to the expectation.
"Protocol" likely returns a string, but cmp will ensure it's a number before
comparing:
"Protocol" likely returns a string, but cmp will ensure it's a number before
comparing:
its('Protocol') { should cmp 2 }
its('Protocol') { should cmp '2' }
its('Protocol') { should cmp 2 }
its('Protocol') { should cmp '2' }
"users" may return an array, but if it contains only one item, cmp will compare
it as a string or number as needed:
"users" may return an array, but if it contains only one item, cmp will compare
it as a string or number as needed:
its('users') { should cmp 'root' }
its('users') { should cmp 'root' }
cmp is not case-sensitive:
cmp is not case-sensitive:
its('log_format') { should cmp 'raw' }
its('log_format') { should cmp 'RAW' }
its('log_format') { should cmp 'raw' }
its('log_format') { should cmp 'RAW' }
#{mark 'eq'}
#{mark 'eq'}
The #{mark 'eq'} matcher tests for exact equality of two values. Value type
(string, number, etc.) is important and must be the same. For a less-restrictive
comparison matcher, use the #{mark 'cmp'} matcher.
The #{mark 'eq'} matcher tests for exact equality of two values. Value type
(string, number, etc.) is important and must be the same. For a less-restrictive
comparison matcher, use the #{mark 'cmp'} matcher.
its('RSAAuthentication') { should_not eq 'no' }
its('RSAAuthentication') { should_not eq 'no' }
#{mark 'include'}
#{mark 'include'}
The #{mark 'include'} matcher tests to see if a value is included in a list.
The #{mark 'include'} matcher tests to see if a value is included in a list.
its('users') { should include 'my_user' }
its('users') { should include 'my_user' }
#{mark 'match'}
#{mark 'match'}
The #{mark 'match'} matcher can be used to test a string for a match using a
regular expression.
The #{mark 'match'} matcher can be used to test a string for a match using a
regular expression.
its('content') { should_not match /^MyKey:\\s+some value/ }
its('content') { should_not match /^MyKey:\\s+some value/ }
For more examples, see: https://www.inspec.io/docs/reference/matchers/
For more examples, see: https://www.inspec.io/docs/reference/matchers/
EOL
end

View file

@ -266,7 +266,7 @@ end
# - compare strings case-insensitive
# - you expect a number (strings will be converted if possible)
#
RSpec::Matchers.define :cmp do |first_expected|
RSpec::Matchers.define :cmp do |first_expected| # rubocop:disable Metrics/BlockLength
def integer?(value)
!(value =~ /\A0+\Z|\A[1-9]\d*\Z/).nil?
@ -324,7 +324,6 @@ RSpec::Matchers.define :cmp do |first_expected|
# fallback to simple operation
actual.method(op).call(expected)
rescue NameError => _
false
rescue ArgumentError

View file

@ -43,9 +43,9 @@ module Inspec::Resources
# find line
target = nil
result.each_line {|s|
result.each_line do |s|
target = s.strip if s =~ /\b.*#{key}.*\b/
}
end
# extract value
values = nil

View file

@ -101,7 +101,8 @@ module Inspec::Resources
'permissions' => perms,
'key' => key,
'fields_nokey' => fields_nokey,
},)
},
)
end
def syscall_rules_for(line)
@ -128,7 +129,8 @@ module Inspec::Resources
'permissions' => perms,
'exit' => exit_field,
'fields_nokey' => fields_nokey,
},)
},
)
end
end
@ -142,7 +144,8 @@ module Inspec::Resources
'file' => file,
'key' => key,
'permissions' => perms,
},)
},
)
end
def to_s

View file

@ -26,8 +26,7 @@ class DhParams < Inspec.resource(1)
def initialize(filename)
@dh_params_path = filename
file = inspec.file(@dh_params_path)
return skip_resource 'Unable to find DH parameters file ' \
"#{@dh_params_path}" unless file.exist?
return skip_resource "Unable to find DH parameters file #{@dh_params_path}" unless file.exist?
begin
@dh_params = OpenSSL::PKey::DH.new file.content

View file

@ -146,7 +146,7 @@ module Inspec::Resources
# @see https://github.com/moby/moby/issues/20625, works for docker 1.13+
# raw_containers = inspec.command('docker ps -a --no-trunc --format \'{{ json . }}\'').stdout
# therefore we stick with older approach
labels = %w{Command CreatedAt ID Image Labels Mounts Names Ports RunningFor Size Status}
labels = %w{Command CreatedAt ID Image Labels Mounts Names Ports RunningFor Size Status}
# Networks LocalVolumes work with 1.13+ only
if !version.empty? && Gem::Version.new(version['Client']['Version']) >= Gem::Version.new('1.13')
@ -183,7 +183,7 @@ module Inspec::Resources
end
def ensure_container_keys(entry)
%w{Command CreatedAt ID Image Labels Mounts Names Ports RunningFor Size Status Networks LocalVolumes}.each { |key|
%w{Command CreatedAt ID Image Labels Mounts Names Ports RunningFor Size Status Networks LocalVolumes}.each { |key|
entry[key.downcase] = nil if !entry.key?(key.downcase)
}
entry

View file

@ -63,10 +63,10 @@ module Inspec::Resources
end
def command
if container_info.entries.length == 1
cmd = container_info.commands[0]
cmd.slice(1, cmd.length - 2)
end
return unless container_info.entries.length == 1
cmd = container_info.commands[0]
cmd.slice(1, cmd.length - 2)
end
def image

View file

@ -154,9 +154,7 @@ module Inspec::Resources
raise 'Connection refused - peer certificate issuer is not recognized'
end
if !cmd.exit_status.zero?
raise "Error fetching Elastcsearch data from curl #{url}: #{cmd.stderr}"
end
raise "Error fetching Elastcsearch data from curl #{url}: #{cmd.stderr}" unless cmd.exit_status.zero?
end
def verify_json_payload!(content)
@ -164,9 +162,7 @@ module Inspec::Resources
raise "#{content['error']['type']}: #{content['error']['reason']}"
end
if content['_nodes']['successful'].zero?
raise 'No successful nodes available in cluster'
end
raise 'No successful nodes available in cluster' if content['_nodes']['successful'].zero?
end
end
end

View file

@ -49,13 +49,11 @@ module Inspec::Resources
end
def groups(filter = nil)
entries = filter || @entries
entries.map { |x| x['name'] } if !entries.nil?
(filter || @entries)&.map { |x| x['name'] }
end
def gids(filter = nil)
entries = filter || @entries
entries.map { |x| x['gid'] } if !entries.nil?
(filter || @entries)&.map { |x| x['gid'] }
end
def users(filter = nil)

View file

@ -157,20 +157,20 @@ module Inspec::Resources
class WindowsGroup < GroupInfo
# returns all local groups
def groups
script = <<-EOH
Function ConvertTo-SID { Param([byte[]]$BinarySID)
(New-Object System.Security.Principal.SecurityIdentifier($BinarySID,0)).Value
}
script = <<~EOH
Function ConvertTo-SID { Param([byte[]]$BinarySID)
(New-Object System.Security.Principal.SecurityIdentifier($BinarySID,0)).Value
}
$Computername = $Env:Computername
$adsi = [ADSI]"WinNT://$Computername"
$groups = $adsi.Children | where {$_.SchemaClassName -eq 'group'} | ForEach {
$name = $_.Name[0]
$sid = ConvertTo-SID -BinarySID $_.ObjectSID[0]
$group =[ADSI]$_.Path
new-object psobject -property @{name = $group.Name[0]; gid = $sid; domain=$Computername}
}
$groups | ConvertTo-Json -Depth 3
$Computername = $Env:Computername
$adsi = [ADSI]"WinNT://$Computername"
$groups = $adsi.Children | where {$_.SchemaClassName -eq 'group'} | ForEach {
$name = $_.Name[0]
$sid = ConvertTo-SID -BinarySID $_.ObjectSID[0]
$group =[ADSI]$_.Path
new-object psobject -property @{name = $group.Name[0]; gid = $sid; domain=$Computername}
}
$groups | ConvertTo-Json -Depth 3
EOH
cmd = inspec.powershell(script)
# cannot rely on exit code for now, successful command returns exit code 1

View file

@ -70,9 +70,8 @@ module Inspec::Resources
end
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(', ')}"
end
return skip_resource 'The following requirements are not met for this resource: ' \
"#{missing_requirements.join(', ')}" unless missing_requirements.empty?
end
def proto

View file

@ -97,7 +97,7 @@ module Inspec::Resources
class Rpms < PkgsManagement
def build_package_list
# use two spaces as delimiter in case any of the fields has a space in it
command = "rpm -qa --queryformat '%{NAME} %{VERSION}-%{RELEASE}\\n'"
command = "rpm -qa --queryformat '%{NAME} %{VERSION}-%{RELEASE}\\n'" # rubocop:disable Style/FormatStringToken
cmd = inspec.command(command)
all = cmd.stdout.split("\n")
return [] if all.nil?

View file

@ -242,7 +242,7 @@ module Inspec::Resources
procs[proc_id] = [] unless procs.key?(proc_id)
# change address '*' to zero
host = (port_id =~ /^ipv6:/) ? '[::]' : '0.0.0.0' if host == '*'
host = port_id =~ /^ipv6:/ ? '[::]' : '0.0.0.0' if host == '*'
# entrust URI to scrub the host and port
begin
uri = URI("addr://#{host}:#{port}")

View file

@ -55,13 +55,13 @@ module Inspec::Resources
private
def verify_dirs
if !inspec.directory(@conf_dir).exist?
warn "Default postgresql configuration directory: #{@conf_dir} does not exist. Postgresql may not be installed or we've misidentified the configuration directory."
end
warn "Default postgresql configuration directory: #{@conf_dir} does not exist. " \
"Postgresql may not be installed or we've misidentified the configuration " \
'directory.' unless inspec.directory(@conf_dir).exist?
if !inspec.directory(@data_dir).exist?
warn "Default postgresql data directory: #{@data_dir} does not exist. Postgresql may not be installed or we've misidentified the data directory."
end
warn "Default postgresql data directory: #{@data_dir} does not exist. " \
"Postgresql may not be installed or we've misidentified the data " \
'directory.' unless inspec.directory(@data_dir).exist?
end
def version_from_psql

View file

@ -34,7 +34,7 @@ module Inspec::Resources
# Removes leading and trailing whitespace from stdout
def strip
result.stdout.strip unless result.stdout.nil?
result.stdout&.strip
end
def to_s

View file

@ -51,7 +51,7 @@ module Inspec::Resources
#
# @return [boolean] true if all runlevels are disabled
def disabled?
!values.any?
values.none?
end
def to_s
@ -136,7 +136,7 @@ module Inspec::Resources
end
elsif %w{redhat fedora centos oracle}.include?(platform)
version = os[:release].to_i
if (%w{ redhat centos oracle }.include?(platform) && version >= 7) || (platform == 'fedora' && version >= 15)
if (%w{redhat centos oracle}.include?(platform) && version >= 7) || (platform == 'fedora' && version >= 15)
Systemd.new(inspec, service_ctl)
else
SysV.new(inspec, service_ctl || '/sbin/service')
@ -314,7 +314,6 @@ module Inspec::Resources
enabled_rc_tcpip? || enabled_inittab?
end
# #rubocop:disable Style/TrailingComma
def enabled_rc_tcpip?
inspec.command(
"grep -v ^# /etc/rc.tcpip | grep 'start ' | grep -Eq '(/{0,1}| )#{name} '",
@ -367,10 +366,10 @@ module Inspec::Resources
end
def version
@version ||= (
@version ||= begin
out = inspec.command("#{service_ctl} --version").stdout
Gem::Version.new(out[/\(upstart ([^\)]+)\)/, 1])
)
end
end
end

View file

@ -575,64 +575,64 @@ module Inspec::Resources
# https://msdn.microsoft.com/en-us/library/aa746340(v=vs.85).aspx
def collect_user_details # rubocop:disable Metrics/MethodLength
return @users_cache if defined?(@users_cache)
script = <<-EOH
Function ConvertTo-SID { Param([byte[]]$BinarySID)
(New-Object System.Security.Principal.SecurityIdentifier($BinarySID,0)).Value
}
script = <<~EOH
Function ConvertTo-SID { Param([byte[]]$BinarySID)
(New-Object System.Security.Principal.SecurityIdentifier($BinarySID,0)).Value
}
Function Convert-UserFlag { Param ($UserFlag)
$List = @()
Switch ($UserFlag) {
($UserFlag -BOR 0x0001) { $List += 'SCRIPT' }
($UserFlag -BOR 0x0002) { $List += 'ACCOUNTDISABLE' }
($UserFlag -BOR 0x0008) { $List += 'HOMEDIR_REQUIRED' }
($UserFlag -BOR 0x0010) { $List += 'LOCKOUT' }
($UserFlag -BOR 0x0020) { $List += 'PASSWD_NOTREQD' }
($UserFlag -BOR 0x0040) { $List += 'PASSWD_CANT_CHANGE' }
($UserFlag -BOR 0x0080) { $List += 'ENCRYPTED_TEXT_PWD_ALLOWED' }
($UserFlag -BOR 0x0100) { $List += 'TEMP_DUPLICATE_ACCOUNT' }
($UserFlag -BOR 0x0200) { $List += 'NORMAL_ACCOUNT' }
($UserFlag -BOR 0x0800) { $List += 'INTERDOMAIN_TRUST_ACCOUNT' }
($UserFlag -BOR 0x1000) { $List += 'WORKSTATION_TRUST_ACCOUNT' }
($UserFlag -BOR 0x2000) { $List += 'SERVER_TRUST_ACCOUNT' }
($UserFlag -BOR 0x10000) { $List += 'DONT_EXPIRE_PASSWORD' }
($UserFlag -BOR 0x20000) { $List += 'MNS_LOGON_ACCOUNT' }
($UserFlag -BOR 0x40000) { $List += 'SMARTCARD_REQUIRED' }
($UserFlag -BOR 0x80000) { $List += 'TRUSTED_FOR_DELEGATION' }
($UserFlag -BOR 0x100000) { $List += 'NOT_DELEGATED' }
($UserFlag -BOR 0x200000) { $List += 'USE_DES_KEY_ONLY' }
($UserFlag -BOR 0x400000) { $List += 'DONT_REQ_PREAUTH' }
($UserFlag -BOR 0x800000) { $List += 'PASSWORD_EXPIRED' }
($UserFlag -BOR 0x1000000) { $List += 'TRUSTED_TO_AUTH_FOR_DELEGATION' }
($UserFlag -BOR 0x04000000) { $List += 'PARTIAL_SECRETS_ACCOUNT' }
}
$List
}
Function Convert-UserFlag { Param ($UserFlag)
$List = @()
Switch ($UserFlag) {
($UserFlag -BOR 0x0001) { $List += 'SCRIPT' }
($UserFlag -BOR 0x0002) { $List += 'ACCOUNTDISABLE' }
($UserFlag -BOR 0x0008) { $List += 'HOMEDIR_REQUIRED' }
($UserFlag -BOR 0x0010) { $List += 'LOCKOUT' }
($UserFlag -BOR 0x0020) { $List += 'PASSWD_NOTREQD' }
($UserFlag -BOR 0x0040) { $List += 'PASSWD_CANT_CHANGE' }
($UserFlag -BOR 0x0080) { $List += 'ENCRYPTED_TEXT_PWD_ALLOWED' }
($UserFlag -BOR 0x0100) { $List += 'TEMP_DUPLICATE_ACCOUNT' }
($UserFlag -BOR 0x0200) { $List += 'NORMAL_ACCOUNT' }
($UserFlag -BOR 0x0800) { $List += 'INTERDOMAIN_TRUST_ACCOUNT' }
($UserFlag -BOR 0x1000) { $List += 'WORKSTATION_TRUST_ACCOUNT' }
($UserFlag -BOR 0x2000) { $List += 'SERVER_TRUST_ACCOUNT' }
($UserFlag -BOR 0x10000) { $List += 'DONT_EXPIRE_PASSWORD' }
($UserFlag -BOR 0x20000) { $List += 'MNS_LOGON_ACCOUNT' }
($UserFlag -BOR 0x40000) { $List += 'SMARTCARD_REQUIRED' }
($UserFlag -BOR 0x80000) { $List += 'TRUSTED_FOR_DELEGATION' }
($UserFlag -BOR 0x100000) { $List += 'NOT_DELEGATED' }
($UserFlag -BOR 0x200000) { $List += 'USE_DES_KEY_ONLY' }
($UserFlag -BOR 0x400000) { $List += 'DONT_REQ_PREAUTH' }
($UserFlag -BOR 0x800000) { $List += 'PASSWORD_EXPIRED' }
($UserFlag -BOR 0x1000000) { $List += 'TRUSTED_TO_AUTH_FOR_DELEGATION' }
($UserFlag -BOR 0x04000000) { $List += 'PARTIAL_SECRETS_ACCOUNT' }
}
$List
}
$Computername = $Env:Computername
$adsi = [ADSI]"WinNT://$Computername"
$adsi.Children | where {$_.SchemaClassName -eq 'user'} | ForEach {
New-Object PSObject -property @{
uid = ConvertTo-SID -BinarySID $_.ObjectSID[0]
username = $_.Name[0]
description = $_.Description[0]
disabled = $_.AccountDisabled[0]
userflags = Convert-UserFlag -UserFlag $_.UserFlags[0]
passwordage = [math]::Round($_.PasswordAge[0]/86400)
minpasswordlength = $_.MinPasswordLength[0]
mindays = [math]::Round($_.MinPasswordAge[0]/86400)
maxdays = [math]::Round($_.MaxPasswordAge[0]/86400)
warndays = $null
badpasswordattempts = $_.BadPasswordAttempts[0]
maxbadpasswords = $_.MaxBadPasswordsAllowed[0]
gid = $null
group = $null
groups = @($_.Groups() | Foreach-Object { $_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null) })
home = $_.HomeDirectory[0]
shell = $null
domain = $Computername
}
} | ConvertTo-Json
$Computername = $Env:Computername
$adsi = [ADSI]"WinNT://$Computername"
$adsi.Children | where {$_.SchemaClassName -eq 'user'} | ForEach {
New-Object PSObject -property @{
uid = ConvertTo-SID -BinarySID $_.ObjectSID[0]
username = $_.Name[0]
description = $_.Description[0]
disabled = $_.AccountDisabled[0]
userflags = Convert-UserFlag -UserFlag $_.UserFlags[0]
passwordage = [math]::Round($_.PasswordAge[0]/86400)
minpasswordlength = $_.MinPasswordLength[0]
mindays = [math]::Round($_.MinPasswordAge[0]/86400)
maxdays = [math]::Round($_.MaxPasswordAge[0]/86400)
warndays = $null
badpasswordattempts = $_.BadPasswordAttempts[0]
maxbadpasswords = $_.MaxBadPasswordsAllowed[0]
gid = $null
group = $null
groups = @($_.Groups() | Foreach-Object { $_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null) })
home = $_.HomeDirectory[0]
shell = $null
domain = $Computername
}
} | ConvertTo-Json
EOH
cmd = inspec.powershell(script)
# cannot rely on exit code for now, successful command returns exit code 1

View file

@ -37,16 +37,16 @@ module Inspec::Resources
def initialize(vbscript)
return skip_resource 'The `vbscript` resource is not supported on your OS yet.' unless inspec.os.windows?
@seperator = SecureRandom.uuid
cmd = <<-EOH
$vbscript = @"
#{vbscript}
Wscript.Stdout.Write "#{@seperator}"
"@
$filename = [System.IO.Path]::GetTempFileName() + ".vbs"
New-Item $filename -type file -force -value $vbscript | Out-Null
cscript.exe /nologo $filename
Remove-Item $filename | Out-Null
EOH
cmd = <<~EOH
$vbscript = @"
#{vbscript}
Wscript.Stdout.Write "#{@seperator}"
"@
$filename = [System.IO.Path]::GetTempFileName() + ".vbs"
New-Item $filename -type file -force -value $vbscript | Out-Null
cscript.exe /nologo $filename
Remove-Item $filename | Out-Null
EOH
super(cmd)
end

View file

@ -76,7 +76,7 @@ module Inspec::Resources
# This file should exist on most Xen systems, normally empty for guests
if inspec.file('/proc/xen/capabilities').exist? &&
inspec.file('/proc/xen/capabilities').content =~ /control_d/i # rubocop:disable Style/MultilineOperationIndentation
inspec.file('/proc/xen/capabilities').content =~ /control_d/i # rubocop:disable Layout/MultilineOperationIndentation
@virtualization_data[:role] = 'host'
end
true
@ -120,11 +120,10 @@ module Inspec::Resources
# guests will have the hypervisor cpu feature that hosts don't have
def detect_kvm_from_sys
return false unless inspec.file('/sys/devices/virtual/misc/kvm').exist?
@virtualization_data[:system] = 'kvm'
if inspec.file('/proc/cpuinfo').content =~ /hypervisor/
@virtualization_data[:system] = 'kvm'
@virtualization_data[:role] = 'guest'
else
@virtualization_data[:system] = 'kvm'
@virtualization_data[:role] = 'host'
end
true
@ -190,7 +189,7 @@ module Inspec::Resources
return false unless inspec.file('/proc/self/cgroup').exist?
cgroup_content = inspec.file('/proc/self/cgroup').content
if cgroup_content =~ %r{^\d+:[^:]+:/(lxc|docker)/.+$} ||
cgroup_content =~ %r{^\d+:[^:]+:/[^/]+/(lxc|docker)-.+$} # rubocop:disable Style/MultilineOperationIndentation
cgroup_content =~ %r{^\d+:[^:]+:/[^/]+/(lxc|docker)-.+$} # rubocop:disable Layout/MultilineOperationIndentation
@virtualization_data[:system] = $1 # rubocop:disable Style/PerlBackrefs
@virtualization_data[:role] = 'guest'
elsif lxc_version_exists? && cgroup_content =~ %r{\d:[^:]+:/$}

View file

@ -52,7 +52,7 @@ module Inspec::Resources
end
# Forward these methods directly to OpenSSL::X509::Certificate instance
%w{version not_before not_after signature_algorithm public_key }.each do |m|
%w{version not_before not_after signature_algorithm public_key}.each do |m|
define_method m.to_sym do |*args|
@cert.method(m.to_sym).call(*args)
end

View file

@ -94,7 +94,7 @@ module Inspec::Resources
# Removes lefthand and righthand whitespace
def strip(value)
value.strip if !value.nil?
value&.strip
end
# Optimize the key value

View file

@ -43,7 +43,8 @@ module SourceReaders
Inspec::Metadata.from_ref(
metadata_source,
@target.read(metadata_source),
nil)
nil,
)
rescue Psych::SyntaxError => e
raise "Unable to parse inspec.yml: line #{e.line}, #{e.problem} #{e.context}"
rescue => e

View file

@ -14,16 +14,11 @@ class CommandWrapper
end
wrap = options[:wrap]
if !wrap.nil? && !wrap.is_a?(Proc)
raise "Called command wrapper with wrap: #{wrap.inspect}. It must be called with a Proc."
elsif !wrap.nil?
return wrap.call(cmd)
end
raise "Called command wrapper with wrap: #{wrap.inspect}. It must be called with a Proc." if !wrap.nil? && !wrap.is_a?(Proc)
return wrap.call(cmd) unless wrap.nil?
shell = options[:shell]
unless UNIX_SHELLS.include?(shell)
raise "Don't know how to wrap commands for shell: #{shell.inspect}."
end
raise "Don't know how to wrap commands for shell: #{shell.inspect}." unless UNIX_SHELLS.include?(shell)
path = options[:path] || shell
args = options[:args] || '-c'

View file

@ -151,7 +151,7 @@ module FilterTable
# the struct to hold single items from the #entries method
entry_struct = Struct.new(*struct_fields.map(&:to_sym)) do
attr_accessor :__filter
def to_s # rubocop:disable Lint/NestedMethodDefinition
def to_s
@__filter || super
end
end unless struct_fields.empty?

View file

@ -12,6 +12,7 @@ class Logger::JSONFormatter < Logger::Formatter
'severity'=> severity,
'time'=> time,
'msg'=> msg,
},)
},
)
end
end

View file

@ -8,14 +8,15 @@ class LatestInSpecVersion
# fetches the latest version from rubygems server
def latest
uri = URI('https://rubygems.org/api/v1/gems/inspec.json')
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
open_timeout: 0.5, read_timeout: 0.5
) {|http|
res = Net::HTTP.start(
uri.host, uri.port, use_ssl: uri.scheme == 'https',
open_timeout: 0.5, read_timeout: 0.5
) { |http|
http.get(uri.path)
}
inspec_info = JSON.parse(res.body)
inspec_info['version']
rescue Exception # rubocop:disable Lint/RescueException
rescue StandardError
nil
end
end

View file

@ -27,7 +27,7 @@ module ObjectTraverser
# If the values to return from is an Array, allow returning by index.
# Otherwise, support methods on the Array itself.
def extract_from_array(key, value)
if key.is_a?(Fixnum)
if key.is_a?(Integer)
value[key]
elsif value.respond_to?(key.to_sym)
value.send(key.to_sym)

View file

@ -234,8 +234,8 @@ module XinetdParser
# extract content line
nl = rest.index("\n") || (rest.length-1)
comment = rest.index('#') || (rest.length-1)
dst_idx = (comment < nl) ? comment : nl
inner_line = (dst_idx == 0) ? '' : rest[0..dst_idx-1].strip
dst_idx = comment < nl ? comment : nl
inner_line = dst_idx == 0 ? '' : rest[0..dst_idx-1].strip
# update unparsed content
rest = rest[nl+1..-1]
next if inner_line.empty?

View file

@ -11,9 +11,9 @@ source 'https://rubygems.org'
# gem 'omnibus-software', github: 'chef/omnibus-software', branch: 'ksubrama/ruby23'
# Use entries from chef's Gemfile
gem 'license_scout', github: 'chef/license_scout'
gem 'omnibus', github: 'chef/omnibus'
gem 'omnibus-software', github: 'chef/omnibus-software'
gem 'license_scout', github: 'chef/license_scout'
# This development group is installed by default when you run `bundle install`,
# but if you are using Omnibus in a CI-based infrastructure, you do not need
@ -24,7 +24,7 @@ group :development do
gem 'berkshelf', '~> 4.3'
# Use Test Kitchen with Vagrant for converging the build environment
gem 'test-kitchen', '~> 1.9'
gem 'kitchen-vagrant', '~> 0.19'
gem 'test-kitchen', '~> 1.9'
gem 'winrm-fs', '~> 0.4'
end

View file

@ -145,7 +145,7 @@ class ResourceDocs
end
end
namespace :docs do
namespace :docs do # rubocop:disable Metrics/BlockLength
desc 'Create cli docs'
task :cli do
# formatter for the output file
@ -171,7 +171,7 @@ namespace :docs do
res << f.p('This subcommand has the following syntax:')
res << f.code("$ inspec #{cmd.usage}", 'bash')
opts = cmd.options.select { |_, o| !o.hide }
opts = cmd.options.reject { |_, o| o.hide }
unless opts.empty?
res << f.h3('Options') + f.p('This subcommand has additional options:')

View file

@ -208,7 +208,6 @@ begin
out
end
# rubocop:enable all
rescue LoadError
STDERR.puts "\n*** TomlRb not available.\n\n"
end

View file

@ -12,23 +12,23 @@ gem 'wdm', '~> 0.1.0', platforms: [:mswin, :mingw]
gem 'tzinfo-data', platforms: [:mswin, :mingw]
# Middleman Gems
gem 'middleman-sprockets', '>= 4.0.0'
gem 'middleman-compass', '>= 4.0.0'
gem 'middleman', '>= 4.0.0'
gem 'middleman-livereload'
gem 'middleman-autoprefixer'
gem 'middleman-compass', '>= 4.0.0'
gem 'middleman-livereload'
gem 'middleman-sprockets', '>= 4.0.0'
gem 'middleman-syntax'
gem 'redcarpet'
# Tutorial Gems
gem 'github-markup'
gem 'docker-api'
gem 'github-markup'
# Build process requirements
gem 'inquirer'
gem 'inspec', path: '..'
gem 'rake'
gem 'ruby-progressbar'
gem 'inquirer'
# Ability to flush the cache during a deploy
gem 'fastly'

2
www/Rakefile Normal file → Executable file
View file

@ -31,7 +31,7 @@ task :default do
exit(1)
end
namespace :www do
namespace :www do # rubocop:disable Metrics/BlockLength
desc 'Builds the tutorial contents'
task :tutorial do
Log.section 'Build the online tutorial in tutorial/'