mirror of
https://github.com/inspec/inspec
synced 2024-11-24 21:53:15 +00:00
blindly applied chefstyle -a
Signed-off-by: Ryan Davis <zenspider@chef.io>
This commit is contained in:
parent
5a0dd5a5d8
commit
a5309ea392
688 changed files with 16796 additions and 16827 deletions
|
@ -1,4 +1,4 @@
|
||||||
source 'https://supermarket.chef.io'
|
source "https://supermarket.chef.io"
|
||||||
|
|
||||||
cookbook 'audit'
|
cookbook "audit"
|
||||||
cookbook 'os_prepare', path: './test/cookbooks/os_prepare'
|
cookbook "os_prepare", path: "./test/cookbooks/os_prepare"
|
||||||
|
|
66
Gemfile
66
Gemfile
|
@ -1,61 +1,61 @@
|
||||||
source 'https://rubygems.org'
|
source "https://rubygems.org"
|
||||||
|
|
||||||
gem 'inspec', path: '.'
|
gem "inspec", path: "."
|
||||||
|
|
||||||
# This dependency is NOT used for normal gem deployment
|
# This dependency is NOT used for normal gem deployment
|
||||||
# - instead, inspec-bin gemspec-depends on inspec
|
# - instead, inspec-bin gemspec-depends on inspec
|
||||||
#
|
#
|
||||||
# However, AppBundler requires a top-level Gemfile.lock with inspec-bin
|
# However, AppBundler requires a top-level Gemfile.lock with inspec-bin
|
||||||
# in it in order to package the executable. Hence the odd backwards dependency.
|
# in it in order to package the executable. Hence the odd backwards dependency.
|
||||||
gem 'inspec-bin', path: './inspec-bin'
|
gem "inspec-bin", path: "./inspec-bin"
|
||||||
|
|
||||||
gem 'ffi', '>= 1.9.14'
|
gem "ffi", ">= 1.9.14"
|
||||||
|
|
||||||
group :omnibus do
|
group :omnibus do
|
||||||
gem 'rb-readline'
|
gem "rb-readline"
|
||||||
gem 'appbundler'
|
gem "appbundler"
|
||||||
gem 'ed25519' # ed25519 ssh key support done here as its a native gem we can't put in the gemspec
|
gem "ed25519" # ed25519 ssh key support done here as its a native gem we can't put in the gemspec
|
||||||
gem 'bcrypt_pbkdf' # ed25519 ssh key support done here as its a native gem we can't put in the gemspec
|
gem "bcrypt_pbkdf" # ed25519 ssh key support done here as its a native gem we can't put in the gemspec
|
||||||
end
|
end
|
||||||
|
|
||||||
group :test do
|
group :test do
|
||||||
gem 'chefstyle', '~> 0.6'
|
gem "chefstyle", "~> 0.6"
|
||||||
gem 'coveralls', require: false
|
gem "coveralls", require: false
|
||||||
gem 'minitest', '~> 5.5'
|
gem "minitest", "~> 5.5"
|
||||||
gem 'rake', '>= 10'
|
gem "rake", ">= 10"
|
||||||
gem 'simplecov', '~> 0.10'
|
gem "simplecov", "~> 0.10"
|
||||||
gem 'concurrent-ruby', '~> 1.0'
|
gem "concurrent-ruby", "~> 1.0"
|
||||||
gem 'mocha', '~> 1.1'
|
gem "mocha", "~> 1.1"
|
||||||
gem 'ruby-progressbar', '~> 1.8'
|
gem "ruby-progressbar", "~> 1.8"
|
||||||
gem 'webmock', '~> 3.0'
|
gem "webmock", "~> 3.0"
|
||||||
gem 'passgen'
|
gem "passgen"
|
||||||
gem 'm'
|
gem "m"
|
||||||
gem 'pry', '~> 0.10'
|
gem "pry", "~> 0.10"
|
||||||
gem 'pry-byebug'
|
gem "pry-byebug"
|
||||||
end
|
end
|
||||||
|
|
||||||
group :integration do
|
group :integration do
|
||||||
gem 'berkshelf'
|
gem "berkshelf"
|
||||||
gem 'chef', '< 15'
|
gem "chef", "< 15"
|
||||||
gem 'test-kitchen'
|
gem "test-kitchen"
|
||||||
gem 'kitchen-vagrant'
|
gem "kitchen-vagrant"
|
||||||
gem 'kitchen-inspec'
|
gem "kitchen-inspec"
|
||||||
gem 'kitchen-ec2'
|
gem "kitchen-ec2"
|
||||||
gem 'kitchen-dokken'
|
gem "kitchen-dokken"
|
||||||
gem 'git'
|
gem "git"
|
||||||
end
|
end
|
||||||
|
|
||||||
# gems for Maintainers.md generation
|
# gems for Maintainers.md generation
|
||||||
group :maintenance do
|
group :maintenance do
|
||||||
gem 'tomlrb'
|
gem "tomlrb"
|
||||||
|
|
||||||
# To sync maintainers with github
|
# To sync maintainers with github
|
||||||
gem 'octokit'
|
gem "octokit"
|
||||||
gem 'netrc'
|
gem "netrc"
|
||||||
end
|
end
|
||||||
|
|
||||||
group :deploy do
|
group :deploy do
|
||||||
gem 'inquirer'
|
gem "inquirer"
|
||||||
end
|
end
|
||||||
|
|
||||||
# add these additional dependencies into Gemfile.local
|
# add these additional dependencies into Gemfile.local
|
||||||
|
|
191
Rakefile
191
Rakefile
|
@ -1,15 +1,15 @@
|
||||||
#!/usr/bin/env rake
|
#!/usr/bin/env rake
|
||||||
|
|
||||||
require 'bundler'
|
require "bundler"
|
||||||
require 'bundler/gem_helper'
|
require "bundler/gem_helper"
|
||||||
require 'rake/testtask'
|
require "rake/testtask"
|
||||||
require 'passgen'
|
require "passgen"
|
||||||
require 'train'
|
require "train"
|
||||||
require_relative 'tasks/maintainers'
|
require_relative "tasks/maintainers"
|
||||||
require_relative 'tasks/spdx'
|
require_relative "tasks/spdx"
|
||||||
require 'fileutils'
|
require "fileutils"
|
||||||
|
|
||||||
Bundler::GemHelper.install_tasks name: 'inspec'
|
Bundler::GemHelper.install_tasks name: "inspec"
|
||||||
|
|
||||||
def prompt(message)
|
def prompt(message)
|
||||||
print(message)
|
print(message)
|
||||||
|
@ -21,17 +21,17 @@ end
|
||||||
# when the "tests" gem group in the Gemfile has been excluded, such as
|
# when the "tests" gem group in the Gemfile has been excluded, such as
|
||||||
# during an appbundle-updater run.
|
# during an appbundle-updater run.
|
||||||
begin
|
begin
|
||||||
require 'ruby-progressbar'
|
require "ruby-progressbar"
|
||||||
require_relative 'tasks/docs'
|
require_relative "tasks/docs"
|
||||||
rescue LoadError
|
rescue LoadError
|
||||||
puts 'docs tasks are unavailable because the ruby-progressbar gem is not available.'
|
puts "docs tasks are unavailable because the ruby-progressbar gem is not available."
|
||||||
end
|
end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
require 'git'
|
require "git"
|
||||||
require_relative 'tasks/contrib'
|
require_relative "tasks/contrib"
|
||||||
rescue LoadError
|
rescue LoadError
|
||||||
puts 'contrib tasks are unavailable because the git gem is not available.'
|
puts "contrib tasks are unavailable because the git gem is not available."
|
||||||
end
|
end
|
||||||
|
|
||||||
task :install do
|
task :install do
|
||||||
|
@ -44,27 +44,27 @@ GLOBS = [
|
||||||
"test/unit/**/*_test.rb",
|
"test/unit/**/*_test.rb",
|
||||||
"test/functional/**/*_test.rb",
|
"test/functional/**/*_test.rb",
|
||||||
"lib/plugins/inspec-*/test/**/*_test.rb",
|
"lib/plugins/inspec-*/test/**/*_test.rb",
|
||||||
]
|
].freeze
|
||||||
|
|
||||||
# run tests
|
# run tests
|
||||||
task default: ['test:lint', 'test:default']
|
task default: ["test:lint", "test:default"]
|
||||||
|
|
||||||
namespace :test do
|
namespace :test do
|
||||||
|
|
||||||
Rake::TestTask.new(:default) do |t|
|
Rake::TestTask.new(:default) do |t|
|
||||||
t.libs << 'test'
|
t.libs << "test"
|
||||||
t.test_files = Dir[*GLOBS].sort
|
t.test_files = Dir[*GLOBS].sort
|
||||||
t.warning = !!ENV["W"]
|
t.warning = !!ENV["W"]
|
||||||
t.verbose = !!ENV["V"] # default to off. the test commands are _huge_.
|
t.verbose = !!ENV["V"] # default to off. the test commands are _huge_.
|
||||||
t.ruby_opts = ['--dev'] if defined?(JRUBY_VERSION)
|
t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION)
|
||||||
end
|
end
|
||||||
task :default => [:accept_license]
|
task default: [:accept_license]
|
||||||
|
|
||||||
begin
|
begin
|
||||||
require 'rubocop/rake_task'
|
require "rubocop/rake_task"
|
||||||
RuboCop::RakeTask.new(:lint)
|
RuboCop::RakeTask.new(:lint)
|
||||||
rescue LoadError
|
rescue LoadError
|
||||||
puts 'rubocop is not available. Install the rubocop gem to run the lint tests.'
|
puts "rubocop is not available. Install the rubocop gem to run the lint tests."
|
||||||
end
|
end
|
||||||
|
|
||||||
task :list do
|
task :list do
|
||||||
|
@ -75,9 +75,9 @@ namespace :test do
|
||||||
clean = true
|
clean = true
|
||||||
|
|
||||||
failures = Dir[*GLOBS]
|
failures = Dir[*GLOBS]
|
||||||
failures.reject! { |file|
|
failures.reject! do |file|
|
||||||
system(Gem.ruby, '-Ilib:test', file)
|
system(Gem.ruby, "-Ilib:test", file)
|
||||||
}
|
end
|
||||||
|
|
||||||
unless failures.empty?
|
unless failures.empty?
|
||||||
puts "These test files failed:\n"
|
puts "These test files failed:\n"
|
||||||
|
@ -87,91 +87,91 @@ namespace :test do
|
||||||
end
|
end
|
||||||
|
|
||||||
task :accept_license do
|
task :accept_license do
|
||||||
FileUtils.mkdir_p(File.join(Dir.home, '.chef', 'accepted_licenses'))
|
FileUtils.mkdir_p(File.join(Dir.home, ".chef", "accepted_licenses"))
|
||||||
# If the user has not accepted the license, touch the acceptance
|
# If the user has not accepted the license, touch the acceptance
|
||||||
# file, but also touch a marker that it is only for testing.
|
# file, but also touch a marker that it is only for testing.
|
||||||
unless File.exist?(File.join(Dir.home, '.chef', 'accepted_licenses', 'inspec'))
|
unless File.exist?(File.join(Dir.home, ".chef", "accepted_licenses", "inspec"))
|
||||||
puts "\n\nTemporarily accepting Chef user license for the duration of testing...\n"
|
puts "\n\nTemporarily accepting Chef user license for the duration of testing...\n"
|
||||||
FileUtils.touch(File.join(Dir.home, '.chef', 'accepted_licenses', 'inspec'))
|
FileUtils.touch(File.join(Dir.home, ".chef", "accepted_licenses", "inspec"))
|
||||||
FileUtils.touch(File.join(Dir.home, '.chef', 'accepted_licenses', 'inspec.for_testing'))
|
FileUtils.touch(File.join(Dir.home, ".chef", "accepted_licenses", "inspec.for_testing"))
|
||||||
end
|
end
|
||||||
|
|
||||||
# Regardless of what happens, when this process exits, check for cleanup.
|
# Regardless of what happens, when this process exits, check for cleanup.
|
||||||
at_exit do
|
at_exit do
|
||||||
if File.exist?(File.join(Dir.home, '.chef', 'accepted_licenses', 'inspec.for_testing'))
|
if File.exist?(File.join(Dir.home, ".chef", "accepted_licenses", "inspec.for_testing"))
|
||||||
puts "\n\nRemoving temporary Chef user license acceptance file that was placed for test duration.\n"
|
puts "\n\nRemoving temporary Chef user license acceptance file that was placed for test duration.\n"
|
||||||
FileUtils.rm_f(File.join(Dir.home, '.chef', 'accepted_licenses', 'inspec'))
|
FileUtils.rm_f(File.join(Dir.home, ".chef", "accepted_licenses", "inspec"))
|
||||||
FileUtils.rm_f(File.join(Dir.home, '.chef', 'accepted_licenses', 'inspec.for_testing'))
|
FileUtils.rm_f(File.join(Dir.home, ".chef", "accepted_licenses", "inspec.for_testing"))
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
Rake::TestTask.new(:functional) do |t|
|
Rake::TestTask.new(:functional) do |t|
|
||||||
t.libs << 'test'
|
t.libs << "test"
|
||||||
t.test_files = Dir.glob([
|
t.test_files = Dir.glob([
|
||||||
'test/functional/**/*_test.rb',
|
"test/functional/**/*_test.rb",
|
||||||
'lib/plugins/inspec-*/test/functional/**/*_test.rb',
|
"lib/plugins/inspec-*/test/functional/**/*_test.rb",
|
||||||
])
|
])
|
||||||
t.warning = !!ENV["W"]
|
t.warning = !!ENV["W"]
|
||||||
t.verbose = !!ENV["V"] # default to off. the test commands are _huge_.
|
t.verbose = !!ENV["V"] # default to off. the test commands are _huge_.
|
||||||
t.ruby_opts = ['--dev'] if defined?(JRUBY_VERSION)
|
t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION)
|
||||||
end
|
end
|
||||||
# Inject a prerequisite task
|
# Inject a prerequisite task
|
||||||
task :functional => [:accept_license]
|
task functional: [:accept_license]
|
||||||
|
|
||||||
Rake::TestTask.new(:unit) do |t|
|
Rake::TestTask.new(:unit) do |t|
|
||||||
t.libs << 'test'
|
t.libs << "test"
|
||||||
t.test_files = Dir.glob([
|
t.test_files = Dir.glob([
|
||||||
'test/unit/**/*_test.rb',
|
"test/unit/**/*_test.rb",
|
||||||
'lib/plugins/inspec-*/test/unit/**/*_test.rb',
|
"lib/plugins/inspec-*/test/unit/**/*_test.rb",
|
||||||
])
|
])
|
||||||
t.warning = !!ENV["W"]
|
t.warning = !!ENV["W"]
|
||||||
t.verbose = !!ENV["V"] # default to off. the test commands are _huge_.
|
t.verbose = !!ENV["V"] # default to off. the test commands are _huge_.
|
||||||
t.ruby_opts = ['--dev'] if defined?(JRUBY_VERSION)
|
t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION)
|
||||||
end
|
end
|
||||||
# Inject a prerequisite task
|
# Inject a prerequisite task
|
||||||
task :unit => [:accept_license]
|
task unit: [:accept_license]
|
||||||
|
|
||||||
task :resources do
|
task :resources do
|
||||||
tests = Dir['test/unit/resource/*_test.rb']
|
tests = Dir["test/unit/resource/*_test.rb"]
|
||||||
return if tests.empty?
|
return if tests.empty?
|
||||||
sh(Gem.ruby, 'test/docker_test.rb', *tests)
|
sh(Gem.ruby, "test/docker_test.rb", *tests)
|
||||||
end
|
end
|
||||||
|
|
||||||
task :integration, [:os] do |task, args|
|
task :integration, [:os] do |task, args|
|
||||||
concurrency = ENV['CONCURRENCY'] || 1
|
concurrency = ENV["CONCURRENCY"] || 1
|
||||||
os = args[:os] || ENV['OS'] || ''
|
os = args[:os] || ENV["OS"] || ""
|
||||||
ENV['DOCKER'] = 'true' if ENV['docker'].nil?
|
ENV["DOCKER"] = "true" if ENV["docker"].nil?
|
||||||
sh("bundle exec kitchen test -c #{concurrency} #{os}")
|
sh("bundle exec kitchen test -c #{concurrency} #{os}")
|
||||||
end
|
end
|
||||||
# Inject a prerequisite task
|
# Inject a prerequisite task
|
||||||
task :'integration' => [:accept_license]
|
task 'integration': [:accept_license]
|
||||||
|
|
||||||
task :ssh, [:target] do |_t, args|
|
task :ssh, [:target] do |_t, args|
|
||||||
tests_path = File.join(File.dirname(__FILE__), 'test', 'integration', 'test', 'integration', 'default')
|
tests_path = File.join(File.dirname(__FILE__), "test", "integration", "test", "integration", "default")
|
||||||
key_files = ENV['key_files'] || File.join(ENV['HOME'], '.ssh', 'id_rsa')
|
key_files = ENV["key_files"] || File.join(ENV["HOME"], ".ssh", "id_rsa")
|
||||||
|
|
||||||
sh_cmd = "bin/inspec exec #{tests_path}/"
|
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 += " --sudo" unless args[:target].split("@")[0] == "root"
|
||||||
sh_cmd += " -t ssh://#{args[:target]}"
|
sh_cmd += " -t ssh://#{args[:target]}"
|
||||||
sh_cmd += " --key_files=#{key_files}"
|
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)
|
sh("sh", "-c", sh_cmd)
|
||||||
end
|
end
|
||||||
|
|
||||||
project_dir = File.dirname(__FILE__)
|
project_dir = File.dirname(__FILE__)
|
||||||
namespace :aws do
|
namespace :aws do
|
||||||
['default', 'minimal'].each do |account|
|
%w{default minimal}.each do |account|
|
||||||
integration_dir = File.join(project_dir, 'test', 'integration', 'aws', account)
|
integration_dir = File.join(project_dir, "test", "integration", "aws", account)
|
||||||
attribute_file = File.join(integration_dir, '.attribute.yml')
|
attribute_file = File.join(integration_dir, ".attribute.yml")
|
||||||
|
|
||||||
task :"setup:#{account}", :tf_workspace do |t, args|
|
task :"setup:#{account}", :tf_workspace do |t, args|
|
||||||
tf_workspace = args[:tf_workspace] || ENV['INSPEC_TERRAFORM_ENV']
|
tf_workspace = args[:tf_workspace] || ENV["INSPEC_TERRAFORM_ENV"]
|
||||||
abort("You must either call the top-level test:aws:#{account} task, or set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
abort("You must either call the top-level test:aws:#{account} task, or set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
||||||
puts "----> Setup"
|
puts "----> Setup"
|
||||||
abort("You must set the environment variable AWS_REGION") unless ENV['AWS_REGION']
|
abort("You must set the environment variable AWS_REGION") unless ENV["AWS_REGION"]
|
||||||
puts "----> Checking for required AWS profile..."
|
puts "----> Checking for required AWS profile..."
|
||||||
sh("aws configure get aws_access_key_id --profile inspec-aws-test-#{account} > /dev/null")
|
sh("aws configure get aws_access_key_id --profile inspec-aws-test-#{account} > /dev/null")
|
||||||
sh("cd #{integration_dir}/build/ && terraform init -upgrade")
|
sh("cd #{integration_dir}/build/ && terraform init -upgrade")
|
||||||
|
@ -185,7 +185,7 @@ namespace :test do
|
||||||
sh("cd #{integration_dir}/build/ && AWS_PROFILE=inspec-aws-test-#{account} terraform output > #{attribute_file}")
|
sh("cd #{integration_dir}/build/ && AWS_PROFILE=inspec-aws-test-#{account} terraform output > #{attribute_file}")
|
||||||
raw_output = File.read(attribute_file)
|
raw_output = File.read(attribute_file)
|
||||||
yaml_output = raw_output.gsub(" = ", " : ")
|
yaml_output = raw_output.gsub(" = ", " : ")
|
||||||
File.open(attribute_file, "w") {|file| file.puts yaml_output}
|
File.open(attribute_file, "w") { |file| file.puts yaml_output }
|
||||||
end
|
end
|
||||||
|
|
||||||
task :"run:#{account}" do
|
task :"run:#{account}" do
|
||||||
|
@ -194,7 +194,7 @@ namespace :test do
|
||||||
end
|
end
|
||||||
|
|
||||||
task :"cleanup:#{account}", :tf_workspace do |t, args|
|
task :"cleanup:#{account}", :tf_workspace do |t, args|
|
||||||
tf_workspace = args[:tf_workspace] || ENV['INSPEC_TERRAFORM_ENV']
|
tf_workspace = args[:tf_workspace] || ENV["INSPEC_TERRAFORM_ENV"]
|
||||||
abort("You must either call the top-level test:aws:#{account} task, or set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
abort("You must either call the top-level test:aws:#{account} task, or set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
||||||
puts "----> Cleanup"
|
puts "----> Cleanup"
|
||||||
sh("cd #{integration_dir}/build/ && AWS_PROFILE=inspec-aws-test-#{account} terraform destroy -force")
|
sh("cd #{integration_dir}/build/ && AWS_PROFILE=inspec-aws-test-#{account} terraform destroy -force")
|
||||||
|
@ -203,14 +203,14 @@ namespace :test do
|
||||||
end
|
end
|
||||||
|
|
||||||
task :"#{account}" do
|
task :"#{account}" do
|
||||||
tf_workspace = ENV['INSPEC_TERRAFORM_ENV'] || prompt("Please enter a workspace for your integration tests to run in: ")
|
tf_workspace = ENV["INSPEC_TERRAFORM_ENV"] || prompt("Please enter a workspace for your integration tests to run in: ")
|
||||||
begin
|
begin
|
||||||
Rake::Task["test:aws:setup:#{account}"].execute({:tf_workspace => tf_workspace})
|
Rake::Task["test:aws:setup:#{account}"].execute({ tf_workspace: tf_workspace })
|
||||||
Rake::Task["test:aws:run:#{account}"].execute
|
Rake::Task["test:aws:run:#{account}"].execute
|
||||||
rescue
|
rescue
|
||||||
abort("Integration testing has failed for the #{account} account")
|
abort("Integration testing has failed for the #{account} account")
|
||||||
ensure
|
ensure
|
||||||
Rake::Task["test:aws:cleanup:#{account}"].execute({:tf_workspace => tf_workspace})
|
Rake::Task["test:aws:cleanup:#{account}"].execute({ tf_workspace: tf_workspace })
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -220,15 +220,15 @@ namespace :test do
|
||||||
|
|
||||||
namespace :azure do
|
namespace :azure do
|
||||||
# Specify the directory for the integration tests
|
# Specify the directory for the integration tests
|
||||||
integration_dir = File.join(project_dir, 'test', 'integration', 'azure')
|
integration_dir = File.join(project_dir, "test", "integration", "azure")
|
||||||
tf_vars_file = File.join(integration_dir, 'build', 'terraform.tfvars')
|
tf_vars_file = File.join(integration_dir, "build", "terraform.tfvars")
|
||||||
attribute_file = File.join(integration_dir, '.attribute.yml')
|
attribute_file = File.join(integration_dir, ".attribute.yml")
|
||||||
|
|
||||||
task :setup, :tf_workspace do |t, args|
|
task :setup, :tf_workspace do |t, args|
|
||||||
tf_workspace = args[:tf_workspace] || ENV['INSPEC_TERRAFORM_ENV']
|
tf_workspace = args[:tf_workspace] || ENV["INSPEC_TERRAFORM_ENV"]
|
||||||
abort("You must either call the top-level test:azure task, or set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
abort("You must either call the top-level test:azure task, or set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
||||||
|
|
||||||
puts '----> Setup Terraform Workspace'
|
puts "----> Setup Terraform Workspace"
|
||||||
|
|
||||||
sh("cd #{integration_dir}/build/ && terraform init -upgrade")
|
sh("cd #{integration_dir}/build/ && terraform init -upgrade")
|
||||||
sh("cd #{integration_dir}/build/ && terraform workspace new #{tf_workspace}")
|
sh("cd #{integration_dir}/build/ && terraform workspace new #{tf_workspace}")
|
||||||
|
@ -243,15 +243,15 @@ namespace :test do
|
||||||
|
|
||||||
next if File.exist?(tf_vars_file)
|
next if File.exist?(tf_vars_file)
|
||||||
|
|
||||||
puts '----> Generating Vars'
|
puts "----> Generating Vars"
|
||||||
|
|
||||||
# Generate Azure crendentials
|
# Generate Azure crendentials
|
||||||
connection = Train.create('azure').connection
|
connection = Train.create("azure").connection
|
||||||
creds = connection.options
|
creds = connection.options
|
||||||
|
|
||||||
# Determine the storage account name and the admin password
|
# Determine the storage account name and the admin password
|
||||||
sa_name = (0...15).map { (65 + rand(26)).chr }.join.downcase
|
sa_name = (0...15).map { (65 + rand(26)).chr }.join.downcase
|
||||||
admin_password = Passgen::generate(length: 12, uppercase: true, lowercase: true, symbols: true, digits: true)
|
admin_password = Passgen.generate(length: 12, uppercase: true, lowercase: true, symbols: true, digits: true)
|
||||||
|
|
||||||
# Use the first 4 characters of the storage account to create a suffix
|
# Use the first 4 characters of the storage account to create a suffix
|
||||||
suffix = sa_name[0..3]
|
suffix = sa_name[0..3]
|
||||||
|
@ -266,17 +266,17 @@ namespace :test do
|
||||||
suffix = "#{suffix}"
|
suffix = "#{suffix}"
|
||||||
VARS
|
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)
|
File.write(tf_vars_file, content)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc "generate plan from state using terraform.tfvars file"
|
desc "generate plan from state using terraform.tfvars file"
|
||||||
task :plan, [:tf_workspace] => [:vars] do |t, args|
|
task :plan, [:tf_workspace] => [:vars] do |t, args|
|
||||||
tf_workspace = args[:tf_workspace] || ENV['INSPEC_TERRAFORM_ENV']
|
tf_workspace = args[:tf_workspace] || ENV["INSPEC_TERRAFORM_ENV"]
|
||||||
abort("You must set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
abort("You must set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
||||||
|
|
||||||
puts '----> Generating Plan'
|
puts "----> Generating Plan"
|
||||||
|
|
||||||
result = sh("cd #{integration_dir}/build/ && terraform workspace select #{tf_workspace}")
|
result = sh("cd #{integration_dir}/build/ && terraform workspace select #{tf_workspace}")
|
||||||
|
|
||||||
|
@ -285,9 +285,9 @@ namespace :test do
|
||||||
|
|
||||||
desc "apply terraform plan"
|
desc "apply terraform plan"
|
||||||
task :apply, [:tf_workspace] => [:plan] do |t, args|
|
task :apply, [:tf_workspace] => [:plan] do |t, args|
|
||||||
tf_workspace = args[:tf_workspace] || ENV['INSPEC_TERRAFORM_ENV']
|
tf_workspace = args[:tf_workspace] || ENV["INSPEC_TERRAFORM_ENV"]
|
||||||
abort("You must set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
abort("You must set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
||||||
puts '----> Applying Plan'
|
puts "----> Applying Plan"
|
||||||
|
|
||||||
sh("cd #{integration_dir}/build/ && terraform workspace select #{tf_workspace}")
|
sh("cd #{integration_dir}/build/ && terraform workspace select #{tf_workspace}")
|
||||||
|
|
||||||
|
@ -296,22 +296,22 @@ namespace :test do
|
||||||
Rake::Task["test:azure:dump_attrs"].execute
|
Rake::Task["test:azure:dump_attrs"].execute
|
||||||
end
|
end
|
||||||
|
|
||||||
task :"dump_attrs" do
|
task :dump_attrs do
|
||||||
sh("cd #{integration_dir}/build/ && terraform output > #{attribute_file}")
|
sh("cd #{integration_dir}/build/ && terraform output > #{attribute_file}")
|
||||||
raw_output = File.read(attribute_file)
|
raw_output = File.read(attribute_file)
|
||||||
yaml_output = raw_output.gsub(" = ", " : ")
|
yaml_output = raw_output.gsub(" = ", " : ")
|
||||||
File.open(attribute_file, "w") {|file| file.puts yaml_output}
|
File.open(attribute_file, "w") { |file| file.puts yaml_output }
|
||||||
end
|
end
|
||||||
|
|
||||||
task :run do
|
task :run do
|
||||||
puts '----> Run'
|
puts "----> Run"
|
||||||
sh("bundle exec inspec exec #{integration_dir}/verify -t azure://1e0b427a-d58b-494e-ae4f-ee558463ebbf")
|
sh("bundle exec inspec exec #{integration_dir}/verify -t azure://1e0b427a-d58b-494e-ae4f-ee558463ebbf")
|
||||||
end
|
end
|
||||||
|
|
||||||
task :cleanup, :tf_workspace do |t, args|
|
task :cleanup, :tf_workspace do |t, args|
|
||||||
tf_workspace = args[:tf_workspace] || ENV['INSPEC_TERRAFORM_ENV']
|
tf_workspace = args[:tf_workspace] || ENV["INSPEC_TERRAFORM_ENV"]
|
||||||
abort("You must either call the top-level test:azure task, or set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
abort("You must either call the top-level test:azure task, or set the INSPEC_TERRAFORM_ENV variable.") unless tf_workspace
|
||||||
puts '----> Cleanup'
|
puts "----> Cleanup"
|
||||||
|
|
||||||
sh("cd #{integration_dir}/build/ && terraform destroy -force ")
|
sh("cd #{integration_dir}/build/ && terraform destroy -force ")
|
||||||
|
|
||||||
|
@ -323,14 +323,14 @@ namespace :test do
|
||||||
|
|
||||||
desc "Perform Azure Integration Tests"
|
desc "Perform Azure Integration Tests"
|
||||||
task :azure do
|
task :azure do
|
||||||
tf_workspace = ENV['INSPEC_TERRAFORM_ENV'] || prompt("Please enter a workspace for your integration tests to run in: ")
|
tf_workspace = ENV["INSPEC_TERRAFORM_ENV"] || prompt("Please enter a workspace for your integration tests to run in: ")
|
||||||
begin
|
begin
|
||||||
Rake::Task["test:azure:setup"].execute({:tf_workspace => tf_workspace})
|
Rake::Task["test:azure:setup"].execute({ tf_workspace: tf_workspace })
|
||||||
Rake::Task["test:azure:run"].execute
|
Rake::Task["test:azure:run"].execute
|
||||||
rescue
|
rescue
|
||||||
abort("Integration testing has failed")
|
abort("Integration testing has failed")
|
||||||
ensure
|
ensure
|
||||||
Rake::Task["test:azure:cleanup"].execute({:tf_workspace => tf_workspace})
|
Rake::Task["test:azure:cleanup"].execute({ tf_workspace: tf_workspace })
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -339,10 +339,10 @@ end
|
||||||
#
|
#
|
||||||
# @param [Type] target the new version you want to set, or nil if you only want to show
|
# @param [Type] target the new version you want to set, or nil if you only want to show
|
||||||
def inspec_version(target = nil)
|
def inspec_version(target = nil)
|
||||||
path = 'lib/inspec/version.rb'
|
path = "lib/inspec/version.rb"
|
||||||
require_relative path.sub(/.rb$/, '')
|
require_relative path.sub(/.rb$/, "")
|
||||||
|
|
||||||
nu_version = target.nil? ? '' : " -> #{target}"
|
nu_version = target.nil? ? "" : " -> #{target}"
|
||||||
puts "Inspec: #{Inspec::VERSION}#{nu_version}"
|
puts "Inspec: #{Inspec::VERSION}#{nu_version}"
|
||||||
|
|
||||||
unless target.nil?
|
unless target.nil?
|
||||||
|
@ -359,7 +359,7 @@ end
|
||||||
# @param [Type] msg the message to display if the command is missing
|
# @param [Type] msg the message to display if the command is missing
|
||||||
def require_command(x, msg = nil)
|
def require_command(x, msg = nil)
|
||||||
return if system("command -v #{x} || exit 1")
|
return if system("command -v #{x} || exit 1")
|
||||||
msg ||= 'Please install it first!'
|
msg ||= "Please install it first!"
|
||||||
puts "\033[31;1mCan't find command #{x.inspect}. #{msg}\033[0m"
|
puts "\033[31;1mCan't find command #{x.inspect}. #{msg}\033[0m"
|
||||||
exit 1
|
exit 1
|
||||||
end
|
end
|
||||||
|
@ -377,16 +377,16 @@ end
|
||||||
|
|
||||||
# Check the requirements for running an update of this repository.
|
# Check the requirements for running an update of this repository.
|
||||||
def check_update_requirements
|
def check_update_requirements
|
||||||
require_command 'git'
|
require_command "git"
|
||||||
end
|
end
|
||||||
|
|
||||||
# Show the current version of this gem.
|
# Show the current version of this gem.
|
||||||
desc 'Show the version of this gem'
|
desc "Show the version of this gem"
|
||||||
task :version do
|
task :version do
|
||||||
inspec_version
|
inspec_version
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'Release a new docker image'
|
desc "Release a new docker image"
|
||||||
task :release_docker do
|
task :release_docker do
|
||||||
version = Inspec::VERSION
|
version = Inspec::VERSION
|
||||||
cmd = "rm *.gem; gem build *gemspec && "\
|
cmd = "rm *.gem; gem build *gemspec && "\
|
||||||
|
@ -396,6 +396,5 @@ task :release_docker do
|
||||||
"docker tag chef/inspec:#{version} chef/inspec:latest &&"\
|
"docker tag chef/inspec:#{version} chef/inspec:latest &&"\
|
||||||
"docker push chef/inspec:latest"
|
"docker push chef/inspec:latest"
|
||||||
puts "--> #{cmd}"
|
puts "--> #{cmd}"
|
||||||
sh('sh', '-c', cmd)
|
sh("sh", "-c", cmd)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
class Batsignal < Inspec.resource(1)
|
class Batsignal < Inspec.resource(1)
|
||||||
name 'batsignal'
|
name "batsignal"
|
||||||
|
|
||||||
example "
|
example "
|
||||||
describe batsignal do
|
describe batsignal do
|
||||||
|
@ -15,6 +15,6 @@ class Batsignal < Inspec.resource(1)
|
||||||
|
|
||||||
def local_command_call
|
def local_command_call
|
||||||
# call out to a core resource
|
# call out to a core resource
|
||||||
inspec.command('echo 4').stdout.to_i
|
inspec.command("echo 4").stdout.to_i
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
class Gordon < Inspec.resource(1)
|
class Gordon < Inspec.resource(1)
|
||||||
name 'gordon'
|
name "gordon"
|
||||||
|
|
||||||
example "
|
example "
|
||||||
describe gordon do
|
describe gordon do
|
||||||
|
@ -18,4 +18,3 @@ class Gordon < Inspec.resource(1)
|
||||||
true
|
true
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
source 'https://rubygems.org'
|
source "https://rubygems.org"
|
||||||
|
|
||||||
gem 'inspec', path: '../../.'
|
gem "inspec", path: "../../."
|
||||||
|
|
||||||
group :test do
|
group :test do
|
||||||
gem 'bundler', '~> 1.5'
|
gem "bundler", "~> 1.5"
|
||||||
gem 'minitest', '~> 5.5'
|
gem "minitest", "~> 5.5"
|
||||||
gem 'rake', '~> 10'
|
gem "rake", "~> 10"
|
||||||
gem 'simplecov', '~> 0.10'
|
gem "simplecov", "~> 0.10"
|
||||||
end
|
end
|
||||||
|
|
||||||
group :integration do
|
group :integration do
|
||||||
gem 'test-kitchen', '~> 1.4'
|
gem "test-kitchen", "~> 1.4"
|
||||||
gem 'kitchen-ansible'
|
gem "kitchen-ansible"
|
||||||
gem 'kitchen-vagrant'
|
gem "kitchen-vagrant"
|
||||||
gem 'kitchen-inspec'
|
gem "kitchen-inspec"
|
||||||
gem 'concurrent-ruby', '~> 1.0'
|
gem "concurrent-ruby", "~> 1.0"
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
# use basic tests
|
# use basic tests
|
||||||
describe package('nginx') do
|
describe package("nginx") do
|
||||||
it { should be_installed }
|
it { should be_installed }
|
||||||
end
|
end
|
||||||
|
|
||||||
# extend tests with metadata
|
# extend tests with metadata
|
||||||
control '01' do
|
control "01" do
|
||||||
impact 0.7
|
impact 0.7
|
||||||
title 'Verify nginx service'
|
title "Verify nginx service"
|
||||||
desc 'Ensures nginx service is up and running'
|
desc "Ensures nginx service is up and running"
|
||||||
describe service('nginx') do
|
describe service("nginx") do
|
||||||
it { should be_enabled }
|
it { should be_enabled }
|
||||||
it { should be_installed }
|
it { should be_installed }
|
||||||
it { should be_running }
|
it { should be_running }
|
||||||
|
@ -16,8 +16,8 @@ control '01' do
|
||||||
end
|
end
|
||||||
|
|
||||||
# implement os dependent tests
|
# implement os dependent tests
|
||||||
web_user = 'www-data'
|
web_user = "www-data"
|
||||||
web_user = 'nginx' if os[:family] == 'centos'
|
web_user = "nginx" if os[:family] == "centos"
|
||||||
|
|
||||||
describe user(web_user) do
|
describe user(web_user) do
|
||||||
it { should exist }
|
it { should exist }
|
||||||
|
|
|
@ -1,3 +1,3 @@
|
||||||
source 'https://supermarket.chef.io'
|
source "https://supermarket.chef.io"
|
||||||
|
|
||||||
metadata
|
metadata
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
source 'https://rubygems.org'
|
source "https://rubygems.org"
|
||||||
|
|
||||||
gem 'inspec', path: '../../.'
|
gem "inspec", path: "../../."
|
||||||
|
|
||||||
group :test do
|
group :test do
|
||||||
gem 'bundler', '~> 1.5'
|
gem "bundler", "~> 1.5"
|
||||||
gem 'minitest', '~> 5.5'
|
gem "minitest", "~> 5.5"
|
||||||
gem 'rake', '~> 10'
|
gem "rake", "~> 10"
|
||||||
gem 'simplecov', '~> 0.10'
|
gem "simplecov", "~> 0.10"
|
||||||
end
|
end
|
||||||
|
|
||||||
group :integration do
|
group :integration do
|
||||||
gem 'berkshelf', '~> 4.0'
|
gem "berkshelf", "~> 4.0"
|
||||||
gem 'test-kitchen', '~> 1.4'
|
gem "test-kitchen", "~> 1.4"
|
||||||
gem 'kitchen-vagrant'
|
gem "kitchen-vagrant"
|
||||||
gem 'kitchen-inspec'
|
gem "kitchen-inspec"
|
||||||
gem 'concurrent-ruby', '~> 0.9'
|
gem "concurrent-ruby", "~> 0.9"
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
name 'prepare'
|
name "prepare"
|
||||||
maintainer 'Chef Software, Inc.'
|
maintainer "Chef Software, Inc."
|
||||||
maintainer_email 'support@chef.io'
|
maintainer_email "support@chef.io"
|
||||||
description 'This cookbook prepares the test operating systems'
|
description "This cookbook prepares the test operating systems"
|
||||||
version '1.0.0'
|
version "1.0.0"
|
||||||
depends 'apt'
|
depends "apt"
|
||||||
depends 'yum'
|
depends "yum"
|
||||||
|
|
|
@ -1,2 +1,2 @@
|
||||||
# install nginx
|
# install nginx
|
||||||
include_recipe('prepare::nginx')
|
include_recipe("prepare::nginx")
|
||||||
|
|
|
@ -1,25 +1,25 @@
|
||||||
# install repositories for nginx
|
# install repositories for nginx
|
||||||
case node['platform']
|
case node["platform"]
|
||||||
when 'ubuntu'
|
when "ubuntu"
|
||||||
# if ubuntu, install
|
# if ubuntu, install
|
||||||
apt_repository 'nginx-php' do
|
apt_repository "nginx-php" do
|
||||||
uri 'ppa:nginx/stable'
|
uri "ppa:nginx/stable"
|
||||||
distribution node['lsb']['codename']
|
distribution node["lsb"]["codename"]
|
||||||
end
|
end
|
||||||
when 'centos'
|
when "centos"
|
||||||
# add repo for Centos 7
|
# add repo for Centos 7
|
||||||
yum_repository 'nginx' do
|
yum_repository "nginx" do
|
||||||
description 'Nginx Repo'
|
description "Nginx Repo"
|
||||||
baseurl 'http://nginx.org/packages/centos/7/x86_64'
|
baseurl "http://nginx.org/packages/centos/7/x86_64"
|
||||||
gpgkey 'http://nginx.org/keys/nginx_signing.key'
|
gpgkey "http://nginx.org/keys/nginx_signing.key"
|
||||||
action :create
|
action :create
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# install nginx package
|
# install nginx package
|
||||||
package 'nginx'
|
package "nginx"
|
||||||
|
|
||||||
# start the service
|
# start the service
|
||||||
service 'nginx' do
|
service "nginx" do
|
||||||
action :start
|
action :start
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
# use basic tests
|
# use basic tests
|
||||||
describe package('nginx') do
|
describe package("nginx") do
|
||||||
it { should be_installed }
|
it { should be_installed }
|
||||||
end
|
end
|
||||||
|
|
||||||
# extend tests with metadata
|
# extend tests with metadata
|
||||||
control '01' do
|
control "01" do
|
||||||
impact 0.7
|
impact 0.7
|
||||||
title 'Verify nginx service'
|
title "Verify nginx service"
|
||||||
desc 'Ensures nginx service is up and running'
|
desc "Ensures nginx service is up and running"
|
||||||
describe service('nginx') do
|
describe service("nginx") do
|
||||||
it { should be_enabled }
|
it { should be_enabled }
|
||||||
it { should be_installed }
|
it { should be_installed }
|
||||||
it { should be_running }
|
it { should be_running }
|
||||||
|
@ -16,8 +16,8 @@ control '01' do
|
||||||
end
|
end
|
||||||
|
|
||||||
# implement os dependent tests
|
# implement os dependent tests
|
||||||
web_user = 'www-data'
|
web_user = "www-data"
|
||||||
web_user = 'nginx' if os[:family] == 'centos'
|
web_user = "nginx" if os[:family] == "centos"
|
||||||
|
|
||||||
describe user(web_user) do
|
describe user(web_user) do
|
||||||
it { should exist }
|
it { should exist }
|
||||||
|
|
|
@ -1,19 +1,19 @@
|
||||||
source 'https://rubygems.org'
|
source "https://rubygems.org"
|
||||||
|
|
||||||
gem 'inspec', path: '../../.'
|
gem "inspec", path: "../../."
|
||||||
|
|
||||||
group :test do
|
group :test do
|
||||||
gem 'bundler', '~> 1.5'
|
gem "bundler", "~> 1.5"
|
||||||
gem 'minitest', '~> 5.5'
|
gem "minitest", "~> 5.5"
|
||||||
gem 'rake', '~> 10'
|
gem "rake", "~> 10"
|
||||||
gem 'simplecov', '~> 0.10'
|
gem "simplecov", "~> 0.10"
|
||||||
end
|
end
|
||||||
|
|
||||||
group :integration do
|
group :integration do
|
||||||
gem 'test-kitchen', '~> 1.4'
|
gem "test-kitchen", "~> 1.4"
|
||||||
gem 'kitchen-vagrant'
|
gem "kitchen-vagrant"
|
||||||
gem 'kitchen-puppet'
|
gem "kitchen-puppet"
|
||||||
gem 'librarian-puppet'
|
gem "librarian-puppet"
|
||||||
gem 'kitchen-inspec'
|
gem "kitchen-inspec"
|
||||||
gem 'concurrent-ruby', '~> 0.9'
|
gem "concurrent-ruby", "~> 0.9"
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
#!/usr/bin/env ruby
|
#!/usr/bin/env ruby
|
||||||
#^syntax detection
|
# ^syntax detection
|
||||||
|
|
||||||
forge "https://forgeapi.puppetlabs.com"
|
forge "https://forgeapi.puppetlabs.com"
|
||||||
|
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
# use basic tests
|
# use basic tests
|
||||||
describe package('nginx') do
|
describe package("nginx") do
|
||||||
it { should be_installed }
|
it { should be_installed }
|
||||||
end
|
end
|
||||||
|
|
||||||
# extend tests with metadata
|
# extend tests with metadata
|
||||||
control '01' do
|
control "01" do
|
||||||
impact 0.7
|
impact 0.7
|
||||||
title 'Verify nginx service'
|
title "Verify nginx service"
|
||||||
desc 'Ensures nginx service is up and running'
|
desc "Ensures nginx service is up and running"
|
||||||
describe service('nginx') do
|
describe service("nginx") do
|
||||||
it { should be_enabled }
|
it { should be_enabled }
|
||||||
it { should be_installed }
|
it { should be_installed }
|
||||||
it { should be_running }
|
it { should be_running }
|
||||||
|
@ -16,8 +16,8 @@ control '01' do
|
||||||
end
|
end
|
||||||
|
|
||||||
# implement os dependent tests
|
# implement os dependent tests
|
||||||
web_user = 'www-data'
|
web_user = "www-data"
|
||||||
web_user = 'nginx' if os[:family] == 'centos'
|
web_user = "nginx" if os[:family] == "centos"
|
||||||
|
|
||||||
describe user(web_user) do
|
describe user(web_user) do
|
||||||
it { should exist }
|
it { should exist }
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
source 'https://rubygems.org'
|
source "https://rubygems.org"
|
||||||
|
|
||||||
gemspec
|
gemspec
|
||||||
|
|
||||||
group :development do
|
group :development do
|
||||||
gem 'bundler'
|
gem "bundler"
|
||||||
gem 'byebug'
|
gem "byebug"
|
||||||
gem 'minitest'
|
gem "minitest"
|
||||||
gem 'rake'
|
gem "rake"
|
||||||
gem 'rubocop', '= 0.49.1' # Need to keep in sync with main InSpec project, so config files will work
|
gem "rubocop", "= 0.49.1" # Need to keep in sync with main InSpec project, so config files will work
|
||||||
end
|
end
|
||||||
|
|
|
@ -7,13 +7,13 @@
|
||||||
|
|
||||||
# This task template will make a task named 'test', and run
|
# This task template will make a task named 'test', and run
|
||||||
# the tests that it finds.
|
# the tests that it finds.
|
||||||
require 'rake/testtask'
|
require "rake/testtask"
|
||||||
|
|
||||||
Rake::TestTask.new do |t|
|
Rake::TestTask.new do |t|
|
||||||
t.libs.push 'lib'
|
t.libs.push "lib"
|
||||||
t.test_files = FileList[
|
t.test_files = FileList[
|
||||||
'test/unit/*_test.rb',
|
"test/unit/*_test.rb",
|
||||||
'test/functional/*_test.rb',
|
"test/functional/*_test.rb",
|
||||||
]
|
]
|
||||||
t.verbose = true
|
t.verbose = true
|
||||||
# Ideally, we'd run tests with warnings enabled,
|
# Ideally, we'd run tests with warnings enabled,
|
||||||
|
@ -26,15 +26,15 @@ end
|
||||||
#------------------------------------------------------------------#
|
#------------------------------------------------------------------#
|
||||||
# Code Style Tasks
|
# Code Style Tasks
|
||||||
#------------------------------------------------------------------#
|
#------------------------------------------------------------------#
|
||||||
require 'rubocop/rake_task'
|
require "rubocop/rake_task"
|
||||||
|
|
||||||
RuboCop::RakeTask.new(:lint) do |t|
|
RuboCop::RakeTask.new(:lint) do |t|
|
||||||
# Choices of rubocop rules to enforce are deeply personal.
|
# Choices of rubocop rules to enforce are deeply personal.
|
||||||
# Here, we set things up so that your plugin will use the Bundler-installed
|
# Here, we set things up so that your plugin will use the Bundler-installed
|
||||||
# inspec gem's copy of the InSpec project's rubocop.yml file (which
|
# inspec gem's copy of the InSpec project's rubocop.yml file (which
|
||||||
# is indeed packaged with the inspec gem).
|
# is indeed packaged with the inspec gem).
|
||||||
require 'inspec/globals'
|
require "inspec/globals"
|
||||||
inspec_rubocop_yml = File.join(Inspec.src_root, '.rubocop.yml')
|
inspec_rubocop_yml = File.join(Inspec.src_root, ".rubocop.yml")
|
||||||
|
|
||||||
t.options = ['--display-cop-names', '--config', inspec_rubocop_yml]
|
t.options = ["--display-cop-names", "--config", inspec_rubocop_yml]
|
||||||
end
|
end
|
||||||
|
|
|
@ -4,23 +4,23 @@
|
||||||
|
|
||||||
# It is traditional in a gemspec to dynamically load the current version
|
# It is traditional in a gemspec to dynamically load the current version
|
||||||
# from a file in the source tree. The next three lines make that happen.
|
# from a file in the source tree. The next three lines make that happen.
|
||||||
lib = File.expand_path('../lib', __FILE__)
|
lib = File.expand_path("../lib", __FILE__)
|
||||||
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
||||||
require 'inspec-resource-lister/version'
|
require "inspec-resource-lister/version"
|
||||||
|
|
||||||
Gem::Specification.new do |spec|
|
Gem::Specification.new do |spec|
|
||||||
# Importantly, all InSpec plugins must be prefixed with `inspec-` (most
|
# Importantly, all InSpec plugins must be prefixed with `inspec-` (most
|
||||||
# plugins) or `train-` (plugins which add new connectivity features).
|
# plugins) or `train-` (plugins which add new connectivity features).
|
||||||
spec.name = 'inspec-resource-lister'
|
spec.name = "inspec-resource-lister"
|
||||||
|
|
||||||
# It is polite to namespace your plugin under InspecPlugins::YourPluginInCamelCase
|
# It is polite to namespace your plugin under InspecPlugins::YourPluginInCamelCase
|
||||||
spec.version = InspecPlugins::ResourceLister::VERSION
|
spec.version = InspecPlugins::ResourceLister::VERSION
|
||||||
spec.authors = ['Clinton Wolfe']
|
spec.authors = ["Clinton Wolfe"]
|
||||||
spec.email = ['cwolfe@chef.io']
|
spec.email = ["cwolfe@chef.io"]
|
||||||
spec.summary = 'InSpec Plugin example, lists available resources'
|
spec.summary = "InSpec Plugin example, lists available resources"
|
||||||
spec.description = 'Example for implementing an InSpec Plugin. This simply lists available resources.'
|
spec.description = "Example for implementing an InSpec Plugin. This simply lists available resources."
|
||||||
spec.homepage = 'https://github.com/inspec/inspec/tree/master/examples/plugin'
|
spec.homepage = "https://github.com/inspec/inspec/tree/master/examples/plugin"
|
||||||
spec.license = 'Apache-2.0'
|
spec.license = "Apache-2.0"
|
||||||
|
|
||||||
# Though complicated-looking, this is pretty standard for a gemspec.
|
# Though complicated-looking, this is pretty standard for a gemspec.
|
||||||
# It just filters what will actually be packaged in the gem (leaving
|
# It just filters what will actually be packaged in the gem (leaving
|
||||||
|
@ -28,9 +28,9 @@ Gem::Specification.new do |spec|
|
||||||
spec.files = %w{
|
spec.files = %w{
|
||||||
README.md inspec-resource-lister.gemspec Gemfile
|
README.md inspec-resource-lister.gemspec Gemfile
|
||||||
} + Dir.glob(
|
} + Dir.glob(
|
||||||
'lib/**/*', File::FNM_DOTMATCH
|
"lib/**/*", File::FNM_DOTMATCH
|
||||||
).reject { |f| File.directory?(f) }
|
).reject { |f| File.directory?(f) }
|
||||||
spec.require_paths = ['lib']
|
spec.require_paths = ["lib"]
|
||||||
|
|
||||||
# If you rely on any other gems, list them here with any constraints.
|
# If you rely on any other gems, list them here with any constraints.
|
||||||
# This is how `inspec plugin install` is able to manage your dependencies.
|
# This is how `inspec plugin install` is able to manage your dependencies.
|
||||||
|
@ -39,5 +39,5 @@ Gem::Specification.new do |spec|
|
||||||
|
|
||||||
# All plugins should mention inspec, > 2.2.78
|
# All plugins should mention inspec, > 2.2.78
|
||||||
# 2.2.78 included the v2 Plugin API
|
# 2.2.78 included the v2 Plugin API
|
||||||
spec.add_dependency 'inspec', '>=2.2.78', '<4.0.0'
|
spec.add_dependency "inspec", ">=2.2.78", "<4.0.0"
|
||||||
end
|
end
|
||||||
|
|
|
@ -11,4 +11,4 @@
|
||||||
libdir = File.dirname(__FILE__)
|
libdir = File.dirname(__FILE__)
|
||||||
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
|
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
|
||||||
|
|
||||||
require 'inspec-resource-lister/plugin'
|
require "inspec-resource-lister/plugin"
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'inspec/resource'
|
require "inspec/resource"
|
||||||
|
|
||||||
module InspecPlugins::ResourceLister
|
module InspecPlugins::ResourceLister
|
||||||
# This class will provide the actual CLI implementation.
|
# This class will provide the actual CLI implementation.
|
||||||
|
@ -16,18 +16,18 @@ module InspecPlugins::ResourceLister
|
||||||
# register the subcommand. Args are a usage message, and a short decription.
|
# register the subcommand. Args are a usage message, and a short decription.
|
||||||
# These will appear when someone has installed the plugin, and then they
|
# These will appear when someone has installed the plugin, and then they
|
||||||
# run `inspec help`.
|
# run `inspec help`.
|
||||||
subcommand_desc 'list-resources [COMMAND]', 'List resources that InSpec finds.'
|
subcommand_desc "list-resources [COMMAND]", "List resources that InSpec finds."
|
||||||
|
|
||||||
# The usual rhythm for a Thor CLI file is description, options, command method.
|
# The usual rhythm for a Thor CLI file is description, options, command method.
|
||||||
# Thor just has you call DSL methods in sequence prior to each command.
|
# Thor just has you call DSL methods in sequence prior to each command.
|
||||||
# Let's make a command, 'core', that lists all of the resources included with InSpec.
|
# Let's make a command, 'core', that lists all of the resources included with InSpec.
|
||||||
|
|
||||||
# First, provide a usage / description. This will appear in `inspec help list-resources`.
|
# First, provide a usage / description. This will appear in `inspec help list-resources`.
|
||||||
desc 'core [OPTIONS]', 'List resources that are included with InSpec.'
|
desc "core [OPTIONS]", "List resources that are included with InSpec."
|
||||||
|
|
||||||
# Let's include an option, -s, to summarize the list.
|
# Let's include an option, -s, to summarize the list.
|
||||||
# Refer to the Thors docs; there is a lot you can do here.
|
# Refer to the Thors docs; there is a lot you can do here.
|
||||||
option :summary, desc: 'Include a total at the bottom', \
|
option :summary, desc: "Include a total at the bottom", \
|
||||||
type: :boolean, default: true, aliases: [:s]
|
type: :boolean, default: true, aliases: [:s]
|
||||||
|
|
||||||
# OK, now the actual method itself. If you provide params, you're telling Thor that
|
# OK, now the actual method itself. If you provide params, you're telling Thor that
|
||||||
|
@ -42,7 +42,7 @@ module InspecPlugins::ResourceLister
|
||||||
# If we were passed a CLI arg, wrap the arg in Regexp matchers so
|
# If we were passed a CLI arg, wrap the arg in Regexp matchers so
|
||||||
# we will match anywhere in the name.
|
# we will match anywhere in the name.
|
||||||
unless pattern == /.+/
|
unless pattern == /.+/
|
||||||
pattern = Regexp.new('.*' + pattern + '.*')
|
pattern = Regexp.new(".*" + pattern + ".*")
|
||||||
end
|
end
|
||||||
|
|
||||||
# This gets a bit into InSpec innards; but this is simply a Hash.
|
# This gets a bit into InSpec innards; but this is simply a Hash.
|
||||||
|
@ -53,7 +53,7 @@ module InspecPlugins::ResourceLister
|
||||||
resource_names.each { |name| puts name }
|
resource_names.each { |name| puts name }
|
||||||
|
|
||||||
if options[:summary]
|
if options[:summary]
|
||||||
puts '-' * 30
|
puts "-" * 30
|
||||||
puts "#{resource_names.count} resources total"
|
puts "#{resource_names.count} resources total"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -7,7 +7,7 @@
|
||||||
# fast and light by only loading heavy things when they are needed.
|
# fast and light by only loading heavy things when they are needed.
|
||||||
|
|
||||||
# Presumably this is light
|
# Presumably this is light
|
||||||
require 'inspec-resource-lister/version'
|
require "inspec-resource-lister/version"
|
||||||
|
|
||||||
# The InspecPlugins namespace is where all plugins should declare themselves.
|
# The InspecPlugins namespace is where all plugins should declare themselves.
|
||||||
# The 'Inspec' capitalization is used throughout the InSpec source code; yes, it's
|
# The 'Inspec' capitalization is used throughout the InSpec source code; yes, it's
|
||||||
|
@ -42,7 +42,7 @@ module InspecPlugins
|
||||||
# functionality.
|
# functionality.
|
||||||
# For example, InSpec will activate this hook when `inspec help` is
|
# For example, InSpec will activate this hook when `inspec help` is
|
||||||
# executed, so that this plugin's usage message will be included in the help.
|
# executed, so that this plugin's usage message will be included in the help.
|
||||||
require 'inspec-resource-lister/cli_command'
|
require "inspec-resource-lister/cli_command"
|
||||||
|
|
||||||
# Having loaded our functionality, return a class that will let the
|
# Having loaded our functionality, return a class that will let the
|
||||||
# CLI engine tap into it.
|
# CLI engine tap into it.
|
||||||
|
|
|
@ -3,6 +3,6 @@
|
||||||
# to learn the current version.
|
# to learn the current version.
|
||||||
module InspecPlugins
|
module InspecPlugins
|
||||||
module ResourceLister
|
module ResourceLister
|
||||||
VERSION = '0.1.0'.freeze
|
VERSION = "0.1.0".freeze
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -4,11 +4,11 @@
|
||||||
# Functional tests generally do not have inside knowledge of how the plugin works.
|
# Functional tests generally do not have inside knowledge of how the plugin works.
|
||||||
|
|
||||||
# Include our test harness
|
# Include our test harness
|
||||||
require_relative '../helper'
|
require_relative "../helper"
|
||||||
|
|
||||||
# Because InSpec is a Spec-style test suite, we're going to use Minitest::Spec
|
# Because InSpec is a Spec-style test suite, we're going to use Minitest::Spec
|
||||||
# here, for familiar look and feel. However, this isn't InSpec (or RSpec) code.
|
# here, for familiar look and feel. However, this isn't InSpec (or RSpec) code.
|
||||||
describe 'inspec list-resources core' do
|
describe "inspec list-resources core" do
|
||||||
# Our helper.rb locates this library from the InSpec install that
|
# Our helper.rb locates this library from the InSpec install that
|
||||||
# Bundler installed for us. If we want its methods, we still must
|
# Bundler installed for us. If we want its methods, we still must
|
||||||
# import it. Including it here will make it available in all child
|
# import it. Including it here will make it available in all child
|
||||||
|
@ -30,7 +30,7 @@ describe 'inspec list-resources core' do
|
||||||
# think that this plugin we are currently testing is installed as a
|
# think that this plugin we are currently testing is installed as a
|
||||||
# user plugin, by writing a plugin config file in a temp dir.
|
# user plugin, by writing a plugin config file in a temp dir.
|
||||||
# To use it, just provide a command line, minus the word `inspec`.
|
# To use it, just provide a command line, minus the word `inspec`.
|
||||||
let (:outcome) { run_inspec_process_with_this_plugin('listresources core') }
|
let (:outcome) { run_inspec_process_with_this_plugin("listresources core") }
|
||||||
|
|
||||||
# Some tests through here use minitest Expectations, which attach to all
|
# Some tests through here use minitest Expectations, which attach to all
|
||||||
# Objects, and begin with 'must' (positive) or 'wont' (negative)
|
# Objects, and begin with 'must' (positive) or 'wont' (negative)
|
||||||
|
@ -40,7 +40,7 @@ describe 'inspec list-resources core' do
|
||||||
|
|
||||||
# A selection of core resources, just spot checking.
|
# A selection of core resources, just spot checking.
|
||||||
# This is an example of using Ruby to define sets of tests.
|
# This is an example of using Ruby to define sets of tests.
|
||||||
['process', 'service', 'user', 'file'].each do |resource_name|
|
%w{process service user file}.each do |resource_name|
|
||||||
it "should mention the '#{resource_name}' resource" do
|
it "should mention the '#{resource_name}' resource" do
|
||||||
outcome.stdout.must_include(resource_name)
|
outcome.stdout.must_include(resource_name)
|
||||||
end
|
end
|
||||||
|
@ -48,7 +48,7 @@ describe 'inspec list-resources core' do
|
||||||
|
|
||||||
# Check for the summary
|
# Check for the summary
|
||||||
it "should mention the summary" do
|
it "should mention the summary" do
|
||||||
outcome.stdout.must_include('resources total')
|
outcome.stdout.must_include("resources total")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -56,19 +56,19 @@ describe 'inspec list-resources core' do
|
||||||
describe "when run with a search pattern that matches things" do
|
describe "when run with a search pattern that matches things" do
|
||||||
# Notice that the command line is changed here:
|
# Notice that the command line is changed here:
|
||||||
# "list all resources that have the word user in them"
|
# "list all resources that have the word user in them"
|
||||||
let (:outcome) { run_inspec_process_with_this_plugin('listresources core user') }
|
let (:outcome) { run_inspec_process_with_this_plugin("listresources core user") }
|
||||||
|
|
||||||
# Should be well-behaved...
|
# Should be well-behaved...
|
||||||
it("should exit successfully") { outcome.exit_status.must_equal(0) }
|
it("should exit successfully") { outcome.exit_status.must_equal(0) }
|
||||||
it("should be silent on stderr") { outcome.stderr.must_be_empty }
|
it("should be silent on stderr") { outcome.stderr.must_be_empty }
|
||||||
|
|
||||||
# Here, we want to know it DID match some things, and NOT some others.
|
# Here, we want to know it DID match some things, and NOT some others.
|
||||||
['user', 'users'].each do |resource_name|
|
%w{user users}.each do |resource_name|
|
||||||
it "should mention the '#{resource_name}' resource" do
|
it "should mention the '#{resource_name}' resource" do
|
||||||
outcome.stdout.must_include(resource_name)
|
outcome.stdout.must_include(resource_name)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
['process', 'service', 'file'].each do |resource_name|
|
%w{process service file}.each do |resource_name|
|
||||||
it "should NOT mention the '#{resource_name}' resource" do
|
it "should NOT mention the '#{resource_name}' resource" do
|
||||||
outcome.stdout.wont_include(resource_name)
|
outcome.stdout.wont_include(resource_name)
|
||||||
end
|
end
|
||||||
|
@ -76,7 +76,7 @@ describe 'inspec list-resources core' do
|
||||||
end
|
end
|
||||||
describe "when run with a search pattern that matches nothing" do
|
describe "when run with a search pattern that matches nothing" do
|
||||||
# Unlikely we'll have a resource with the string 'autogyro' in it.
|
# Unlikely we'll have a resource with the string 'autogyro' in it.
|
||||||
let (:outcome) { run_inspec_process_with_this_plugin('listresources core autogyro') }
|
let (:outcome) { run_inspec_process_with_this_plugin("listresources core autogyro") }
|
||||||
|
|
||||||
# Should be well-behaved...
|
# Should be well-behaved...
|
||||||
it("should exit successfully") { outcome.exit_status.must_equal(0) }
|
it("should exit successfully") { outcome.exit_status.must_equal(0) }
|
||||||
|
@ -89,14 +89,14 @@ describe 'inspec list-resources core' do
|
||||||
|
|
||||||
# Check for the summary
|
# Check for the summary
|
||||||
it "should mention a zero-resource summary" do
|
it "should mention a zero-resource summary" do
|
||||||
outcome.stdout.must_include('0 resources total')
|
outcome.stdout.must_include("0 resources total")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# Exercise the summary option, which defaults to 'true'.
|
# Exercise the summary option, which defaults to 'true'.
|
||||||
describe "when run with the no-summary flag" do
|
describe "when run with the no-summary flag" do
|
||||||
# Alter the command string to include the no-summary option
|
# Alter the command string to include the no-summary option
|
||||||
let(:outcome) { run_inspec_process_with_this_plugin('listresources core --no-summary') }
|
let(:outcome) { run_inspec_process_with_this_plugin("listresources core --no-summary") }
|
||||||
|
|
||||||
# Should be well-behaved...
|
# Should be well-behaved...
|
||||||
it("should exit successfully") { outcome.exit_status.must_equal(0) }
|
it("should exit successfully") { outcome.exit_status.must_equal(0) }
|
||||||
|
@ -104,7 +104,7 @@ describe 'inspec list-resources core' do
|
||||||
|
|
||||||
# Check for the summary
|
# Check for the summary
|
||||||
it "should NOT mention summary" do
|
it "should NOT mention summary" do
|
||||||
outcome.stdout.wont_include('0 resources total')
|
outcome.stdout.wont_include("0 resources total")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -6,11 +6,11 @@
|
||||||
# InSpec core provides a number of such libraries and facilities, in the file
|
# InSpec core provides a number of such libraries and facilities, in the file
|
||||||
# lib/pligins/shared/core_plugin_test_helper.rb . So, one job in this file is
|
# lib/pligins/shared/core_plugin_test_helper.rb . So, one job in this file is
|
||||||
# to locate and load that file.
|
# to locate and load that file.
|
||||||
require 'inspec/../plugins/shared/core_plugin_test_helper'
|
require "inspec/../plugins/shared/core_plugin_test_helper"
|
||||||
|
|
||||||
# Also load the InSpec plugin system. We need this so we can unit-test the plugin
|
# Also load the InSpec plugin system. We need this so we can unit-test the plugin
|
||||||
# classes, which will rely on the plugin system.
|
# classes, which will rely on the plugin system.
|
||||||
require 'inspec/plugin/v2'
|
require "inspec/plugin/v2"
|
||||||
|
|
||||||
# Caution: loading all of InSpec (i.e. require 'inspec') may cause interference with
|
# Caution: loading all of InSpec (i.e. require 'inspec') may cause interference with
|
||||||
# minitest/spec; one symptom would be appearing to have no tests.
|
# minitest/spec; one symptom would be appearing to have no tests.
|
||||||
|
@ -19,8 +19,8 @@ require 'inspec/plugin/v2'
|
||||||
# You can select from a number of test harnesses. Since InSpec uses Spec-style controls
|
# You can select from a number of test harnesses. Since InSpec uses Spec-style controls
|
||||||
# in profile code, you will probably want to use something like minitest/spec, which provides
|
# in profile code, you will probably want to use something like minitest/spec, which provides
|
||||||
# Spec-style tests.
|
# Spec-style tests.
|
||||||
require 'minitest/spec'
|
require "minitest/spec"
|
||||||
require 'minitest/autorun'
|
require "minitest/autorun"
|
||||||
|
|
||||||
# You might want to put some debugging tools here. We run tests to find bugs, after all.
|
# You might want to put some debugging tools here. We run tests to find bugs, after all.
|
||||||
# require 'byebug'
|
# require 'byebug'
|
||||||
|
|
|
@ -2,10 +2,10 @@
|
||||||
# inspec-resource-lister are correct.
|
# inspec-resource-lister are correct.
|
||||||
|
|
||||||
# Include our test harness
|
# Include our test harness
|
||||||
require_relative '../helper'
|
require_relative "../helper"
|
||||||
|
|
||||||
# Load the class under test, the CliCommand definition.
|
# Load the class under test, the CliCommand definition.
|
||||||
require 'inspec-resource-lister/cli_command'
|
require "inspec-resource-lister/cli_command"
|
||||||
|
|
||||||
# Because InSpec is a Spec-style test suite, we're going to use Minitest::Spec
|
# Because InSpec is a Spec-style test suite, we're going to use Minitest::Spec
|
||||||
# here, for familiar look and feel. However, this isn't InSpec (or RSpec) code.
|
# here, for familiar look and feel. However, this isn't InSpec (or RSpec) code.
|
||||||
|
@ -20,11 +20,11 @@ describe InspecPlugins::ResourceLister::CliCommand do
|
||||||
let(:cli_class) { InspecPlugins::ResourceLister::CliCommand }
|
let(:cli_class) { InspecPlugins::ResourceLister::CliCommand }
|
||||||
|
|
||||||
# This is a Hash of Structs that tells us details of options for the 'core' subcommand.
|
# This is a Hash of Structs that tells us details of options for the 'core' subcommand.
|
||||||
let(:core_options) { cli_class.all_commands['core'].options }
|
let(:core_options) { cli_class.all_commands["core"].options }
|
||||||
|
|
||||||
# To group tests together, you can nest 'describe' in minitest/spec
|
# To group tests together, you can nest 'describe' in minitest/spec
|
||||||
# (that is discouraged in InSpec control code.)
|
# (that is discouraged in InSpec control code.)
|
||||||
describe 'the core command' do
|
describe "the core command" do
|
||||||
|
|
||||||
# Some tests through here use minitest Expectations, which attach to all
|
# Some tests through here use minitest Expectations, which attach to all
|
||||||
# Objects, and begin with 'must' (positive) or 'wont' (negative)
|
# Objects, and begin with 'must' (positive) or 'wont' (negative)
|
||||||
|
|
|
@ -2,10 +2,10 @@
|
||||||
# the inspec-resource-lister plugin is configured correctly.
|
# the inspec-resource-lister plugin is configured correctly.
|
||||||
|
|
||||||
# Include our test harness
|
# Include our test harness
|
||||||
require_relative '../helper'
|
require_relative "../helper"
|
||||||
|
|
||||||
# Load the class under test, the Plugin definition.
|
# Load the class under test, the Plugin definition.
|
||||||
require 'inspec-resource-lister/plugin'
|
require "inspec-resource-lister/plugin"
|
||||||
|
|
||||||
# Because InSpec is a Spec-style test suite, we're going to use Minitest::Spec
|
# Because InSpec is a Spec-style test suite, we're going to use Minitest::Spec
|
||||||
# here, for familiar look and feel. However, this isn't InSpec (or RSpec) code.
|
# here, for familiar look and feel. However, this isn't InSpec (or RSpec) code.
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
require 'yaml'
|
require "yaml"
|
||||||
|
|
||||||
# Custom resource based on the InSpec resource DSL
|
# Custom resource based on the InSpec resource DSL
|
||||||
class GordonConfig < Inspec.resource(1)
|
class GordonConfig < Inspec.resource(1)
|
||||||
name 'gordon_config'
|
name "gordon_config"
|
||||||
|
|
||||||
supports platform: 'unix'
|
supports platform: "unix"
|
||||||
supports platform: 'windows'
|
supports platform: "windows"
|
||||||
|
|
||||||
desc "
|
desc "
|
||||||
Gordon's resource description ...
|
Gordon's resource description ...
|
||||||
|
@ -21,7 +21,7 @@ class GordonConfig < Inspec.resource(1)
|
||||||
# Load the configuration file on initialization
|
# Load the configuration file on initialization
|
||||||
def initialize
|
def initialize
|
||||||
@params = {}
|
@params = {}
|
||||||
@path = '/tmp/gordon/config.yaml'
|
@path = "/tmp/gordon/config.yaml"
|
||||||
@file = inspec.file(@path)
|
@file = inspec.file(@path)
|
||||||
|
|
||||||
unless @file.file?
|
unless @file.file?
|
||||||
|
@ -32,9 +32,9 @@ class GordonConfig < Inspec.resource(1)
|
||||||
begin
|
begin
|
||||||
@params = YAML.load(@file.content)
|
@params = YAML.load(@file.content)
|
||||||
# Add two extra matchers
|
# Add two extra matchers
|
||||||
@params['file_size'] = @file.size
|
@params["file_size"] = @file.size
|
||||||
@params['file_path'] = @path
|
@params["file_path"] = @path
|
||||||
@params['ruby'] = 'RUBY IS HERE TO HELP ME!'
|
@params["ruby"] = "RUBY IS HERE TO HELP ME!"
|
||||||
rescue StandardError => e
|
rescue StandardError => e
|
||||||
raise Inspec::Exceptions::ResourceSkipped, "#{@file}: #{e.message}"
|
raise Inspec::Exceptions::ResourceSkipped, "#{@file}: #{e.message}"
|
||||||
end
|
end
|
||||||
|
@ -49,7 +49,7 @@ class GordonConfig < Inspec.resource(1)
|
||||||
# Example matcher for the number of commas in the file
|
# Example matcher for the number of commas in the file
|
||||||
def comma_count
|
def comma_count
|
||||||
text = @file.content
|
text = @file.content
|
||||||
text.count(',')
|
text.count(",")
|
||||||
end
|
end
|
||||||
|
|
||||||
# Expose all parameters
|
# Expose all parameters
|
||||||
|
|
|
@ -1,2 +1,2 @@
|
||||||
source 'https://rubygems.org'
|
source "https://rubygems.org"
|
||||||
gemspec name: 'inspec-bin'
|
gemspec name: "inspec-bin"
|
||||||
|
|
|
@ -4,9 +4,9 @@
|
||||||
Encoding.default_external = Encoding::UTF_8
|
Encoding.default_external = Encoding::UTF_8
|
||||||
Encoding.default_internal = Encoding::UTF_8
|
Encoding.default_internal = Encoding::UTF_8
|
||||||
|
|
||||||
lib = File.expand_path('../lib', __FILE__)
|
lib = File.expand_path("../lib", __FILE__)
|
||||||
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
||||||
|
|
||||||
require 'inspec'
|
require "inspec"
|
||||||
require 'inspec/cli'
|
require "inspec/cli"
|
||||||
Inspec::InspecCLI.start(ARGV)
|
Inspec::InspecCLI.start(ARGV)
|
||||||
|
|
|
@ -1,27 +1,27 @@
|
||||||
lib = File.expand_path('../lib', __FILE__)
|
lib = File.expand_path("../lib", __FILE__)
|
||||||
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
||||||
require 'inspec-bin/version'
|
require "inspec-bin/version"
|
||||||
|
|
||||||
Gem::Specification.new do |spec|
|
Gem::Specification.new do |spec|
|
||||||
spec.name = 'inspec-bin'
|
spec.name = "inspec-bin"
|
||||||
spec.version = InspecBin::VERSION
|
spec.version = InspecBin::VERSION
|
||||||
spec.authors = ['Chef InSpec Core Engineering ']
|
spec.authors = ["Chef InSpec Core Engineering "]
|
||||||
spec.email = ['inspec@chef.io']
|
spec.email = ["inspec@chef.io"]
|
||||||
spec.summary = 'Infrastructure and compliance testing.'
|
spec.summary = "Infrastructure and compliance testing."
|
||||||
spec.description = 'InSpec executable for inspec gem. Use of this executable may require accepting a license agreement.'
|
spec.description = "InSpec executable for inspec gem. Use of this executable may require accepting a license agreement."
|
||||||
spec.homepage = 'https://github.com/inspec/inspec/tree/master/inspec-bin'
|
spec.homepage = "https://github.com/inspec/inspec/tree/master/inspec-bin"
|
||||||
spec.license = 'Apache-2.0'
|
spec.license = "Apache-2.0"
|
||||||
|
|
||||||
spec.require_paths = ['lib']
|
spec.require_paths = ["lib"]
|
||||||
spec.required_ruby_version = '>= 2.4'
|
spec.required_ruby_version = ">= 2.4"
|
||||||
|
|
||||||
spec.add_dependency 'inspec', "= #{InspecBin::VERSION}"
|
spec.add_dependency "inspec", "= #{InspecBin::VERSION}"
|
||||||
spec.add_development_dependency 'rake'
|
spec.add_development_dependency "rake"
|
||||||
|
|
||||||
spec.files = %w{README.md LICENSE Gemfile} + Dir.glob('*.gemspec') +
|
spec.files = %w{README.md LICENSE Gemfile} + Dir.glob("*.gemspec") +
|
||||||
Dir.glob('{lib,bin}/**/*', File::FNM_DOTMATCH).reject { |f| File.directory?(f) }
|
Dir.glob("{lib,bin}/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) }
|
||||||
|
|
||||||
spec.bindir = 'bin'
|
spec.bindir = "bin"
|
||||||
spec.executables = %w{inspec}
|
spec.executables = %w{inspec}
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,30 +1,30 @@
|
||||||
lib = File.expand_path('../lib', __FILE__)
|
lib = File.expand_path("../lib", __FILE__)
|
||||||
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
||||||
require 'inspec-bin/version'
|
require "inspec-bin/version"
|
||||||
|
|
||||||
# This is just link inspec-bin, but relies on inspec-core instead of inspec
|
# This is just link inspec-bin, but relies on inspec-core instead of inspec
|
||||||
# inspec-core is a stripped-down version of the inspec gem with fewer exotic dependencies
|
# inspec-core is a stripped-down version of the inspec gem with fewer exotic dependencies
|
||||||
|
|
||||||
Gem::Specification.new do |spec|
|
Gem::Specification.new do |spec|
|
||||||
spec.name = 'inspec-core-bin' # dallas multi-pass
|
spec.name = "inspec-core-bin" # dallas multi-pass
|
||||||
spec.version = InspecBin::VERSION
|
spec.version = InspecBin::VERSION
|
||||||
spec.authors = ['Chef InSpec Core Engineering ']
|
spec.authors = ["Chef InSpec Core Engineering "]
|
||||||
spec.email = ['inspec@chef.io']
|
spec.email = ["inspec@chef.io"]
|
||||||
spec.summary = 'Infrastructure and compliance testing.'
|
spec.summary = "Infrastructure and compliance testing."
|
||||||
spec.description = 'InSpec executable for inspec-core gem. Use of this executable may require accepting a license agreement.'
|
spec.description = "InSpec executable for inspec-core gem. Use of this executable may require accepting a license agreement."
|
||||||
spec.homepage = 'https://github.com/inspec/inspec/tree/master/inspec-bin'
|
spec.homepage = "https://github.com/inspec/inspec/tree/master/inspec-bin"
|
||||||
spec.license = 'Apache-2.0'
|
spec.license = "Apache-2.0"
|
||||||
|
|
||||||
spec.require_paths = ['lib']
|
spec.require_paths = ["lib"]
|
||||||
spec.required_ruby_version = '>= 2.4'
|
spec.required_ruby_version = ">= 2.4"
|
||||||
|
|
||||||
spec.add_dependency 'inspec-core', "= #{InspecBin::VERSION}"
|
spec.add_dependency "inspec-core", "= #{InspecBin::VERSION}"
|
||||||
spec.add_development_dependency 'rake'
|
spec.add_development_dependency "rake"
|
||||||
|
|
||||||
spec.files = %w{README.md LICENSE Gemfile} + ['inspec-core-bin.gemspec'] +
|
spec.files = %w{README.md LICENSE Gemfile} + ["inspec-core-bin.gemspec"] +
|
||||||
Dir.glob('{lib,bin}/**/*', File::FNM_DOTMATCH).reject { |f| File.directory?(f) }
|
Dir.glob("{lib,bin}/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) }
|
||||||
|
|
||||||
spec.bindir = 'bin'
|
spec.bindir = "bin"
|
||||||
spec.executables = %w{inspec}
|
spec.executables = %w{inspec}
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
# This file managed by automation - do not edit manually
|
# This file managed by automation - do not edit manually
|
||||||
module InspecBin
|
module InspecBin
|
||||||
INSPECBIN_ROOT = File.expand_path('../..', __FILE__)
|
INSPECBIN_ROOT = File.expand_path("../..", __FILE__)
|
||||||
VERSION = '4.5.1'.freeze
|
VERSION = "4.5.1".freeze
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,46 +1,46 @@
|
||||||
lib = File.expand_path('../lib', __FILE__)
|
lib = File.expand_path("../lib", __FILE__)
|
||||||
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
||||||
require 'inspec/version'
|
require "inspec/version"
|
||||||
|
|
||||||
Gem::Specification.new do |spec|
|
Gem::Specification.new do |spec|
|
||||||
spec.name = 'inspec-core'
|
spec.name = "inspec-core"
|
||||||
spec.version = Inspec::VERSION
|
spec.version = Inspec::VERSION
|
||||||
spec.authors = ['Dominik Richter']
|
spec.authors = ["Dominik Richter"]
|
||||||
spec.email = ['dominik.richter@gmail.com']
|
spec.email = ["dominik.richter@gmail.com"]
|
||||||
spec.summary = 'Just InSpec'
|
spec.summary = "Just InSpec"
|
||||||
spec.description = 'Core InSpec, local support only. See `inspec` for full support.'
|
spec.description = "Core InSpec, local support only. See `inspec` for full support."
|
||||||
spec.homepage = 'https://github.com/chef/inspec'
|
spec.homepage = "https://github.com/chef/inspec"
|
||||||
spec.license = 'Apache-2.0'
|
spec.license = "Apache-2.0"
|
||||||
|
|
||||||
spec.files = %w{README.md LICENSE} + Dir.glob('{bin,lib,etc}/**/*', File::FNM_DOTMATCH)
|
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']
|
spec.require_paths = ["lib"]
|
||||||
|
|
||||||
spec.required_ruby_version = '>= 2.4'
|
spec.required_ruby_version = ">= 2.4"
|
||||||
|
|
||||||
spec.add_dependency 'train-core', '~> 2.0'
|
spec.add_dependency "train-core", "~> 2.0"
|
||||||
spec.add_dependency 'license-acceptance', '>= 0.2.13', '< 2.0'
|
spec.add_dependency "license-acceptance", ">= 0.2.13", "< 2.0"
|
||||||
spec.add_dependency 'thor', '~> 0.20'
|
spec.add_dependency "thor", "~> 0.20"
|
||||||
spec.add_dependency 'json-schema', '~> 2.8'
|
spec.add_dependency "json-schema", "~> 2.8"
|
||||||
spec.add_dependency 'method_source', '~> 0.8'
|
spec.add_dependency "method_source", "~> 0.8"
|
||||||
spec.add_dependency 'rubyzip', '~> 1.1'
|
spec.add_dependency "rubyzip", "~> 1.1"
|
||||||
spec.add_dependency 'rspec', '~> 3'
|
spec.add_dependency "rspec", "~> 3"
|
||||||
spec.add_dependency 'rspec-its', '~> 1.2'
|
spec.add_dependency "rspec-its", "~> 1.2"
|
||||||
spec.add_dependency 'hashie', '~> 3.4'
|
spec.add_dependency "hashie", "~> 3.4"
|
||||||
spec.add_dependency 'mixlib-log'
|
spec.add_dependency "mixlib-log"
|
||||||
spec.add_dependency 'pry', '~> 0'
|
spec.add_dependency "pry", "~> 0"
|
||||||
spec.add_dependency 'sslshake', '~> 1.2'
|
spec.add_dependency "sslshake", "~> 1.2"
|
||||||
spec.add_dependency 'parallel', '~> 1.9'
|
spec.add_dependency "parallel", "~> 1.9"
|
||||||
spec.add_dependency 'faraday', '>=0.9.0'
|
spec.add_dependency "faraday", ">=0.9.0"
|
||||||
spec.add_dependency 'faraday_middleware', '~> 0.12.2'
|
spec.add_dependency "faraday_middleware", "~> 0.12.2"
|
||||||
spec.add_dependency 'tomlrb', '~> 1.2'
|
spec.add_dependency "tomlrb", "~> 1.2"
|
||||||
spec.add_dependency 'addressable', '~> 2.4'
|
spec.add_dependency "addressable", "~> 2.4"
|
||||||
spec.add_dependency 'parslet', '~> 1.5'
|
spec.add_dependency "parslet", "~> 1.5"
|
||||||
spec.add_dependency 'semverse'
|
spec.add_dependency "semverse"
|
||||||
spec.add_dependency 'htmlentities'
|
spec.add_dependency "htmlentities"
|
||||||
spec.add_dependency 'multipart-post'
|
spec.add_dependency "multipart-post"
|
||||||
spec.add_dependency 'tty-table', '~> 0.10'
|
spec.add_dependency "tty-table", "~> 0.10"
|
||||||
spec.add_dependency 'tty-prompt', '~> 0.17'
|
spec.add_dependency "tty-prompt", "~> 0.17"
|
||||||
spec.add_dependency 'term-ansicolor'
|
spec.add_dependency "term-ansicolor"
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,56 +1,56 @@
|
||||||
lib = File.expand_path('../lib', __FILE__)
|
lib = File.expand_path("../lib", __FILE__)
|
||||||
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
||||||
require 'inspec/version'
|
require "inspec/version"
|
||||||
|
|
||||||
Gem::Specification.new do |spec|
|
Gem::Specification.new do |spec|
|
||||||
spec.name = 'inspec'
|
spec.name = "inspec"
|
||||||
spec.version = Inspec::VERSION
|
spec.version = Inspec::VERSION
|
||||||
spec.authors = ['Chef InSpec Team']
|
spec.authors = ["Chef InSpec Team"]
|
||||||
spec.email = ['inspec@chef.io']
|
spec.email = ["inspec@chef.io"]
|
||||||
spec.summary = 'Infrastructure and compliance testing.'
|
spec.summary = "Infrastructure and compliance testing."
|
||||||
spec.description = 'InSpec provides a framework for creating end-to-end infrastructure tests. You can use it for integration or even compliance testing. Create fully portable test profiles and use them in your workflow to ensure stability and security. Integrate InSpec in your change lifecycle for local testing, CI/CD, and deployment verification.'
|
spec.description = "InSpec provides a framework for creating end-to-end infrastructure tests. You can use it for integration or even compliance testing. Create fully portable test profiles and use them in your workflow to ensure stability and security. Integrate InSpec in your change lifecycle for local testing, CI/CD, and deployment verification."
|
||||||
spec.homepage = 'https://github.com/inspec/inspec'
|
spec.homepage = "https://github.com/inspec/inspec"
|
||||||
spec.license = 'Apache-2.0'
|
spec.license = "Apache-2.0"
|
||||||
|
|
||||||
# the gemfile and gemspec are necessary for appbundler so don't remove it
|
# the gemfile and gemspec are necessary for appbundler so don't remove it
|
||||||
spec.files = %w{Gemfile inspec.gemspec README.md LICENSE} + Dir.glob(
|
spec.files = %w{Gemfile inspec.gemspec README.md LICENSE} + Dir.glob(
|
||||||
'{bin,lib,etc}/**/*', File::FNM_DOTMATCH
|
"{bin,lib,etc}/**/*", File::FNM_DOTMATCH
|
||||||
).reject { |f| File.directory?(f) }
|
).reject { |f| File.directory?(f) }
|
||||||
|
|
||||||
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
|
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.require_paths = ["lib"]
|
||||||
|
|
||||||
spec.required_ruby_version = '>= 2.4'
|
spec.required_ruby_version = ">= 2.4"
|
||||||
|
|
||||||
spec.add_dependency 'train', '~> 2.0' # Inspec 4 must have train 2+
|
spec.add_dependency "train", "~> 2.0" # Inspec 4 must have train 2+
|
||||||
# Train plugins we ship with InSpec
|
# Train plugins we ship with InSpec
|
||||||
spec.add_dependency 'train-habitat', '~> 0.1'
|
spec.add_dependency "train-habitat", "~> 0.1"
|
||||||
spec.add_dependency 'train-aws', '~> 0.1'
|
spec.add_dependency "train-aws", "~> 0.1"
|
||||||
|
|
||||||
# Implementation dependencies
|
# Implementation dependencies
|
||||||
spec.add_dependency 'license-acceptance', '>= 0.2.13', '< 2.0'
|
spec.add_dependency "license-acceptance", ">= 0.2.13", "< 2.0"
|
||||||
spec.add_dependency 'thor', '~> 0.20'
|
spec.add_dependency "thor", "~> 0.20"
|
||||||
spec.add_dependency 'json-schema', '~> 2.8'
|
spec.add_dependency "json-schema", "~> 2.8"
|
||||||
spec.add_dependency 'method_source', '~> 0.8'
|
spec.add_dependency "method_source", "~> 0.8"
|
||||||
spec.add_dependency 'rubyzip', '~> 1.2', '>= 1.2.2'
|
spec.add_dependency "rubyzip", "~> 1.2", ">= 1.2.2"
|
||||||
spec.add_dependency 'rspec', '~> 3'
|
spec.add_dependency "rspec", "~> 3"
|
||||||
spec.add_dependency 'rspec-its', '~> 1.2'
|
spec.add_dependency "rspec-its", "~> 1.2"
|
||||||
spec.add_dependency 'pry', '~> 0'
|
spec.add_dependency "pry", "~> 0"
|
||||||
spec.add_dependency 'hashie', '~> 3.4'
|
spec.add_dependency "hashie", "~> 3.4"
|
||||||
spec.add_dependency 'mixlib-log'
|
spec.add_dependency "mixlib-log"
|
||||||
spec.add_dependency 'sslshake', '~> 1.2'
|
spec.add_dependency "sslshake", "~> 1.2"
|
||||||
spec.add_dependency 'parallel', '~> 1.9'
|
spec.add_dependency "parallel", "~> 1.9"
|
||||||
spec.add_dependency 'faraday', '>=0.9.0'
|
spec.add_dependency "faraday", ">=0.9.0"
|
||||||
spec.add_dependency 'tty-table', '~> 0.10'
|
spec.add_dependency "tty-table", "~> 0.10"
|
||||||
spec.add_dependency 'tty-prompt', '~> 0.17'
|
spec.add_dependency "tty-prompt", "~> 0.17"
|
||||||
# Used for Azure profile until integrated into train
|
# Used for Azure profile until integrated into train
|
||||||
spec.add_dependency 'faraday_middleware', '~> 0.12.2'
|
spec.add_dependency "faraday_middleware", "~> 0.12.2"
|
||||||
spec.add_dependency 'tomlrb', '~> 1.2'
|
spec.add_dependency "tomlrb", "~> 1.2"
|
||||||
spec.add_dependency 'addressable', '~> 2.4'
|
spec.add_dependency "addressable", "~> 2.4"
|
||||||
spec.add_dependency 'parslet', '~> 1.5'
|
spec.add_dependency "parslet", "~> 1.5"
|
||||||
spec.add_dependency 'semverse'
|
spec.add_dependency "semverse"
|
||||||
spec.add_dependency 'htmlentities'
|
spec.add_dependency "htmlentities"
|
||||||
spec.add_dependency 'multipart-post'
|
spec.add_dependency "multipart-post"
|
||||||
spec.add_dependency 'term-ansicolor'
|
spec.add_dependency "term-ansicolor"
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
source 'https://www.rubygems.org'
|
source "https://www.rubygems.org"
|
||||||
|
|
||||||
gem 'kitchen-docker'
|
gem "kitchen-docker"
|
||||||
gem 'test-kitchen'
|
gem "test-kitchen"
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
||||||
# TODO: Remove in inspec 4.0
|
# TODO: Remove in inspec 4.0
|
||||||
|
|
||||||
require 'plugins/inspec-compliance/lib/inspec-compliance/api'
|
require "plugins/inspec-compliance/lib/inspec-compliance/api"
|
||||||
|
|
||||||
# Backport old namespace
|
# Backport old namespace
|
||||||
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
||||||
# TODO: Remove in inspec 4.0
|
# TODO: Remove in inspec 4.0
|
||||||
|
|
||||||
require 'plugins/inspec-compliance/lib/inspec-compliance/configuration'
|
require "plugins/inspec-compliance/lib/inspec-compliance/configuration"
|
||||||
|
|
||||||
# Backport old namespace
|
# Backport old namespace
|
||||||
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
||||||
# TODO: Remove in inspec 4.0
|
# TODO: Remove in inspec 4.0
|
||||||
|
|
||||||
require 'plugins/inspec-compliance/lib/inspec-compliance/http'
|
require "plugins/inspec-compliance/lib/inspec-compliance/http"
|
||||||
|
|
||||||
# Backport old namespace
|
# Backport old namespace
|
||||||
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
||||||
# TODO: Remove in inspec 4.0
|
# TODO: Remove in inspec 4.0
|
||||||
|
|
||||||
require 'plugins/inspec-compliance/lib/inspec-compliance/support'
|
require "plugins/inspec-compliance/lib/inspec-compliance/support"
|
||||||
|
|
||||||
# Backport old namespace
|
# Backport old namespace
|
||||||
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
# This file has been moved to the v2.0 plugins. This redirect allows for legacy use.
|
||||||
# TODO: Remove in inspec 4.0
|
# TODO: Remove in inspec 4.0
|
||||||
|
|
||||||
require 'plugins/inspec-compliance/lib/inspec-compliance/target'
|
require "plugins/inspec-compliance/lib/inspec-compliance/target"
|
||||||
|
|
||||||
# Backport old namespace
|
# Backport old namespace
|
||||||
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
Compliance = InspecPlugins::Compliance unless defined?(Compliance)
|
||||||
|
|
|
@ -2,8 +2,8 @@ libdir = File.dirname(__FILE__)
|
||||||
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
|
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
|
||||||
|
|
||||||
module Supermarket
|
module Supermarket
|
||||||
autoload :API, 'inspec-supermarket/api'
|
autoload :API, "inspec-supermarket/api"
|
||||||
end
|
end
|
||||||
|
|
||||||
require 'inspec-supermarket/cli'
|
require "inspec-supermarket/cli"
|
||||||
require 'inspec-supermarket/target'
|
require "inspec-supermarket/target"
|
||||||
|
|
|
@ -1,23 +1,23 @@
|
||||||
# frozen_string_literal: true
|
# frozen_string_literal: true
|
||||||
|
|
||||||
require 'net/http'
|
require "net/http"
|
||||||
require 'addressable/uri'
|
require "addressable/uri"
|
||||||
|
|
||||||
module Supermarket
|
module Supermarket
|
||||||
class API
|
class API
|
||||||
SUPERMARKET_URL = 'https://supermarket.chef.io'
|
SUPERMARKET_URL = "https://supermarket.chef.io"
|
||||||
|
|
||||||
# displays a list of profiles
|
# displays a list of profiles
|
||||||
def self.profiles(supermarket_url = SUPERMARKET_URL)
|
def self.profiles(supermarket_url = SUPERMARKET_URL)
|
||||||
url = "#{supermarket_url}/api/v1/tools-search"
|
url = "#{supermarket_url}/api/v1/tools-search"
|
||||||
_success, data = get(url, { type: 'compliance_profile', items: 100 })
|
_success, data = get(url, { type: "compliance_profile", items: 100 })
|
||||||
if !data.nil?
|
if !data.nil?
|
||||||
profiles = JSON.parse(data)
|
profiles = JSON.parse(data)
|
||||||
profiles['items'].map { |x|
|
profiles["items"].map do |x|
|
||||||
m = %r{^#{supermarket_url}/api/v1/tools/(?<slug>[\w-]+)(/)?$}.match(x['tool'])
|
m = %r{^#{supermarket_url}/api/v1/tools/(?<slug>[\w-]+)(/)?$}.match(x["tool"])
|
||||||
x['slug'] = m[:slug]
|
x["slug"] = m[:slug]
|
||||||
x
|
x
|
||||||
}
|
end
|
||||||
else
|
else
|
||||||
[]
|
[]
|
||||||
end
|
end
|
||||||
|
@ -51,7 +51,7 @@ module Supermarket
|
||||||
|
|
||||||
# Tool name in Supermarket URL is downcased so we need to downcase
|
# Tool name in Supermarket URL is downcased so we need to downcase
|
||||||
tool = "#{supermarket_url}/api/v1/tools/#{tool_name.downcase}"
|
tool = "#{supermarket_url}/api/v1/tools/#{tool_name.downcase}"
|
||||||
supermarket_tool['tool_owner'] == tool_owner && supermarket_tool['tool'] == tool
|
supermarket_tool["tool_owner"] == tool_owner && supermarket_tool["tool"] == tool
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.find(profile, supermarket_url = SUPERMARKET_URL)
|
def self.find(profile, supermarket_url = SUPERMARKET_URL)
|
||||||
|
@ -77,7 +77,7 @@ module Supermarket
|
||||||
|
|
||||||
def self.send_request(uri, req)
|
def self.send_request(uri, req)
|
||||||
# send request
|
# send request
|
||||||
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
|
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
|
||||||
http.request(req)
|
http.request(req)
|
||||||
end
|
end
|
||||||
[res.is_a?(Net::HTTPSuccess), res.body]
|
[res.is_a?(Net::HTTPSuccess), res.body]
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
require 'inspec/base_cli'
|
require "inspec/base_cli"
|
||||||
|
|
||||||
module Supermarket
|
module Supermarket
|
||||||
class SupermarketCLI < Inspec::BaseCLI
|
class SupermarketCLI < Inspec::BaseCLI
|
||||||
namespace 'supermarket'
|
namespace "supermarket"
|
||||||
|
|
||||||
# TODO: find another solution, once https://github.com/erikhuda/thor/issues/261 is fixed
|
# TODO: find another solution, once https://github.com/erikhuda/thor/issues/261 is fixed
|
||||||
def self.banner(command, _namespace = nil, _subcommand = false)
|
def self.banner(command, _namespace = nil, _subcommand = false)
|
||||||
|
@ -13,18 +13,18 @@ module Supermarket
|
||||||
namespace
|
namespace
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'profiles', 'list all available profiles in Chef Supermarket'
|
desc "profiles", "list all available profiles in Chef Supermarket"
|
||||||
def profiles
|
def profiles
|
||||||
# display profiles in format user/profile
|
# display profiles in format user/profile
|
||||||
supermarket_profiles = Supermarket::API.profiles
|
supermarket_profiles = Supermarket::API.profiles
|
||||||
|
|
||||||
headline('Available profiles:')
|
headline("Available profiles:")
|
||||||
supermarket_profiles.each { |p|
|
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
|
end
|
||||||
|
|
||||||
desc 'exec PROFILE', 'execute a Supermarket profile'
|
desc "exec PROFILE", "execute a Supermarket profile"
|
||||||
exec_options
|
exec_options
|
||||||
def exec(*tests)
|
def exec(*tests)
|
||||||
o = config
|
o = config
|
||||||
|
@ -32,7 +32,7 @@ module Supermarket
|
||||||
configure_logger(o)
|
configure_logger(o)
|
||||||
|
|
||||||
# iterate over tests and add compliance scheme
|
# iterate over tests and add compliance scheme
|
||||||
tests = tests.map { |t| 'supermarket://' + t }
|
tests = tests.map { |t| "supermarket://" + t }
|
||||||
|
|
||||||
runner = Inspec::Runner.new(o)
|
runner = Inspec::Runner.new(o)
|
||||||
tests.each { |target| runner.add_target(target) }
|
tests.each { |target| runner.add_target(target) }
|
||||||
|
@ -43,13 +43,13 @@ module Supermarket
|
||||||
exit 1
|
exit 1
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'info PROFILE', 'display Supermarket profile details'
|
desc "info PROFILE", "display Supermarket profile details"
|
||||||
def info(profile)
|
def info(profile)
|
||||||
# check that the profile is available
|
# check that the profile is available
|
||||||
supermarket_profiles = Supermarket::API.profiles
|
supermarket_profiles = Supermarket::API.profiles
|
||||||
found = supermarket_profiles.select { |p|
|
found = supermarket_profiles.select do |p|
|
||||||
profile == "#{p['tool_owner']}/#{p['slug']}"
|
profile == "#{p['tool_owner']}/#{p['slug']}"
|
||||||
}
|
end
|
||||||
|
|
||||||
if found.empty?
|
if found.empty?
|
||||||
puts "#{mark_text(profile)} is not available on Supermarket"
|
puts "#{mark_text(profile)} is not available on Supermarket"
|
||||||
|
@ -67,5 +67,5 @@ module Supermarket
|
||||||
end
|
end
|
||||||
|
|
||||||
# register the subcommand to InSpec CLI registry
|
# register the subcommand to InSpec CLI registry
|
||||||
Inspec::Plugins::CLI.add_subcommand(SupermarketCLI, 'supermarket', 'supermarket SUBCOMMAND ...', 'Supermarket commands', {})
|
Inspec::Plugins::CLI.add_subcommand(SupermarketCLI, "supermarket", "supermarket SUBCOMMAND ...", "Supermarket commands", {})
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
require 'uri'
|
require "uri"
|
||||||
require 'inspec/fetcher'
|
require "inspec/fetcher"
|
||||||
require 'fetchers/url'
|
require "fetchers/url"
|
||||||
|
|
||||||
# InSpec Target Helper for Supermarket
|
# InSpec Target Helper for Supermarket
|
||||||
module Supermarket
|
module Supermarket
|
||||||
class Fetcher < Inspec.fetcher(1)
|
class Fetcher < Inspec.fetcher(1)
|
||||||
name 'supermarket'
|
name "supermarket"
|
||||||
priority 500
|
priority 500
|
||||||
|
|
||||||
def self.resolve(target, opts = {})
|
def self.resolve(target, opts = {})
|
||||||
supermarket_uri, supermarket_server = if target.is_a?(String) && URI(target).scheme == 'supermarket'
|
supermarket_uri, supermarket_server = if target.is_a?(String) && URI(target).scheme == "supermarket"
|
||||||
[target, Supermarket::API::SUPERMARKET_URL]
|
[target, Supermarket::API::SUPERMARKET_URL]
|
||||||
elsif target.respond_to?(:key?) && target.key?(:supermarket)
|
elsif target.respond_to?(:key?) && target.key?(:supermarket)
|
||||||
supermarket_server = target[:supermarket_url] || Supermarket::API::SUPERMARKET_URL
|
supermarket_server = target[:supermarket_url] || Supermarket::API::SUPERMARKET_URL
|
||||||
|
@ -18,13 +18,13 @@ module Supermarket
|
||||||
return nil unless supermarket_uri
|
return nil unless supermarket_uri
|
||||||
return nil unless Supermarket::API.exist?(supermarket_uri, supermarket_server)
|
return nil unless Supermarket::API.exist?(supermarket_uri, supermarket_server)
|
||||||
tool_info = Supermarket::API.find(supermarket_uri, supermarket_server)
|
tool_info = Supermarket::API.find(supermarket_uri, supermarket_server)
|
||||||
resolve_next(tool_info['tool_source_url'], opts)
|
resolve_next(tool_info["tool_source_url"], opts)
|
||||||
rescue URI::Error
|
rescue URI::Error
|
||||||
nil
|
nil
|
||||||
end
|
end
|
||||||
|
|
||||||
def to_s
|
def to_s
|
||||||
'Chef Compliance Profile Loader'
|
"Chef Compliance Profile Loader"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
require 'tmpdir'
|
require "tmpdir"
|
||||||
require 'fileutils'
|
require "fileutils"
|
||||||
require 'mixlib/shellout'
|
require "mixlib/shellout"
|
||||||
require 'inspec/log'
|
require "inspec/log"
|
||||||
|
|
||||||
module Fetchers
|
module Fetchers
|
||||||
#
|
#
|
||||||
|
@ -24,12 +24,12 @@ module Fetchers
|
||||||
# omnibus source for hints.
|
# omnibus source for hints.
|
||||||
#
|
#
|
||||||
class Git < Inspec.fetcher(1)
|
class Git < Inspec.fetcher(1)
|
||||||
name 'git'
|
name "git"
|
||||||
priority 200
|
priority 200
|
||||||
|
|
||||||
def self.resolve(target, opts = {})
|
def self.resolve(target, opts = {})
|
||||||
if target.is_a?(String)
|
if target.is_a?(String)
|
||||||
new(target, opts) if target.start_with?('git@') || target.end_with?('.git')
|
new(target, opts) if target.start_with?("git@") || target.end_with?(".git")
|
||||||
elsif target.respond_to?(:has_key?) && target.key?(:git)
|
elsif target.respond_to?(:has_key?) && target.key?(:git)
|
||||||
new(target[:git], opts.merge(target))
|
new(target[:git], opts.merge(target))
|
||||||
end
|
end
|
||||||
|
@ -53,7 +53,7 @@ module Fetchers
|
||||||
Dir.mktmpdir do |tmpdir|
|
Dir.mktmpdir do |tmpdir|
|
||||||
checkout(tmpdir)
|
checkout(tmpdir)
|
||||||
Inspec::Log.debug("Checkout of #{resolved_ref} successful. Moving checkout to #{dir}")
|
Inspec::Log.debug("Checkout of #{resolved_ref} successful. Moving checkout to #{dir}")
|
||||||
FileUtils.cp_r(tmpdir + '/.', @repo_directory)
|
FileUtils.cp_r(tmpdir + "/.", @repo_directory)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@repo_directory
|
@repo_directory
|
||||||
|
@ -81,7 +81,7 @@ module Fetchers
|
||||||
elsif @tag
|
elsif @tag
|
||||||
resolve_ref(@tag)
|
resolve_ref(@tag)
|
||||||
else
|
else
|
||||||
resolve_ref('master')
|
resolve_ref("master")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -129,7 +129,7 @@ module Fetchers
|
||||||
end
|
end
|
||||||
|
|
||||||
def cloned?
|
def cloned?
|
||||||
File.directory?(File.join(@repo_directory, '.git'))
|
File.directory?(File.join(@repo_directory, ".git"))
|
||||||
end
|
end
|
||||||
|
|
||||||
def clone(dir = @repo_directory)
|
def clone(dir = @repo_directory)
|
||||||
|
@ -148,7 +148,7 @@ module Fetchers
|
||||||
cmd.error!
|
cmd.error!
|
||||||
cmd.status
|
cmd.status
|
||||||
rescue Errno::ENOENT
|
rescue Errno::ENOENT
|
||||||
raise 'To use git sources, you must have git installed.'
|
raise "To use git sources, you must have git installed."
|
||||||
end
|
end
|
||||||
|
|
||||||
def shellout(cmd, opts = {})
|
def shellout(cmd, opts = {})
|
||||||
|
@ -156,12 +156,12 @@ module Fetchers
|
||||||
cmd = Mixlib::ShellOut.new(cmd, opts)
|
cmd = Mixlib::ShellOut.new(cmd, opts)
|
||||||
cmd.run_command
|
cmd.run_command
|
||||||
Inspec::Log.debug("External command: completed with exit status: #{cmd.exitstatus}")
|
Inspec::Log.debug("External command: completed with exit status: #{cmd.exitstatus}")
|
||||||
Inspec::Log.debug('External command: STDOUT BEGIN')
|
Inspec::Log.debug("External command: STDOUT BEGIN")
|
||||||
Inspec::Log.debug(cmd.stdout)
|
Inspec::Log.debug(cmd.stdout)
|
||||||
Inspec::Log.debug('External command: STDOUT END')
|
Inspec::Log.debug("External command: STDOUT END")
|
||||||
Inspec::Log.debug('External command: STDERR BEGIN')
|
Inspec::Log.debug("External command: STDERR BEGIN")
|
||||||
Inspec::Log.debug(cmd.stderr)
|
Inspec::Log.debug(cmd.stderr)
|
||||||
Inspec::Log.debug('External command: STDERR END')
|
Inspec::Log.debug("External command: STDERR END")
|
||||||
cmd
|
cmd
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
require 'openssl'
|
require "openssl"
|
||||||
|
|
||||||
module Fetchers
|
module Fetchers
|
||||||
class Local < Inspec.fetcher(1)
|
class Local < Inspec.fetcher(1)
|
||||||
name 'local'
|
name "local"
|
||||||
priority 0
|
priority 0
|
||||||
|
|
||||||
def self.resolve(target)
|
def self.resolve(target)
|
||||||
|
@ -27,11 +27,11 @@ module Fetchers
|
||||||
|
|
||||||
def self.resolve_from_string(target)
|
def self.resolve_from_string(target)
|
||||||
# Support "urls" in the form of file://
|
# Support "urls" in the form of file://
|
||||||
if target.start_with?('file://')
|
if target.start_with?("file://")
|
||||||
target = target.gsub(%r{^file://}, '')
|
target = target.gsub(%r{^file://}, "")
|
||||||
else
|
else
|
||||||
# support for windows paths
|
# support for windows paths
|
||||||
target = target.tr('\\', '/')
|
target = target.tr('\\', "/")
|
||||||
end
|
end
|
||||||
|
|
||||||
target if File.exist?(File.expand_path(target))
|
target if File.exist?(File.expand_path(target))
|
||||||
|
@ -101,7 +101,7 @@ module Fetchers
|
||||||
end
|
end
|
||||||
|
|
||||||
def perform_shasum(target)
|
def perform_shasum(target)
|
||||||
@archive_shasum ||= OpenSSL::Digest::SHA256.digest(File.read(target)).unpack('H*')[0]
|
@archive_shasum ||= OpenSSL::Digest::SHA256.digest(File.read(target)).unpack("H*")[0]
|
||||||
end
|
end
|
||||||
|
|
||||||
def resolved_source
|
def resolved_source
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
module Fetchers
|
module Fetchers
|
||||||
class Mock < Inspec.fetcher(1)
|
class Mock < Inspec.fetcher(1)
|
||||||
name 'mock'
|
name "mock"
|
||||||
priority 0
|
priority 0
|
||||||
|
|
||||||
def self.resolve(target)
|
def self.resolve(target)
|
||||||
|
@ -25,7 +25,7 @@ module Fetchers
|
||||||
end
|
end
|
||||||
|
|
||||||
def cache_key
|
def cache_key
|
||||||
''
|
""
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
require 'uri'
|
require "uri"
|
||||||
require 'openssl'
|
require "openssl"
|
||||||
require 'tempfile'
|
require "tempfile"
|
||||||
require 'open-uri'
|
require "open-uri"
|
||||||
|
|
||||||
module Fetchers
|
module Fetchers
|
||||||
class Url < Inspec.fetcher(1)
|
class Url < Inspec.fetcher(1)
|
||||||
MIME_TYPES = {
|
MIME_TYPES = {
|
||||||
'application/x-zip-compressed' => '.zip',
|
"application/x-zip-compressed" => ".zip",
|
||||||
'application/zip' => '.zip',
|
"application/zip" => ".zip",
|
||||||
'application/x-gzip' => '.tar.gz',
|
"application/x-gzip" => ".tar.gz",
|
||||||
'application/gzip' => '.tar.gz',
|
"application/gzip" => ".tar.gz",
|
||||||
}.freeze
|
}.freeze
|
||||||
|
|
||||||
name 'url'
|
name "url"
|
||||||
priority 200
|
priority 200
|
||||||
|
|
||||||
def self.resolve(target, opts = {})
|
def self.resolve(target, opts = {})
|
||||||
|
@ -27,7 +27,7 @@ module Fetchers
|
||||||
|
|
||||||
def self.resolve_from_string(target, opts, username = nil, password = nil)
|
def self.resolve_from_string(target, opts, username = nil, password = nil)
|
||||||
uri = URI.parse(target)
|
uri = URI.parse(target)
|
||||||
return nil if uri.nil? or uri.scheme.nil?
|
return nil if uri.nil? || uri.scheme.nil?
|
||||||
return nil unless %{ http https }.include? uri.scheme
|
return nil unless %{ http https }.include? uri.scheme
|
||||||
target = transform(target)
|
target = transform(target)
|
||||||
opts[:username] = username if username
|
opts[:username] = username if username
|
||||||
|
@ -62,11 +62,11 @@ module Fetchers
|
||||||
# https://bitbucket.org/username/repo/commits/95ce1f83d5bbe9eec34c5973f6894617e8d6d8cc is transformed to
|
# https://bitbucket.org/username/repo/commits/95ce1f83d5bbe9eec34c5973f6894617e8d6d8cc is transformed to
|
||||||
# https://bitbucket.org/username/repo/get/95ce1f83d5bbe9eec34c5973f6894617e8d6d8cc.tar.gz
|
# https://bitbucket.org/username/repo/get/95ce1f83d5bbe9eec34c5973f6894617e8d6d8cc.tar.gz
|
||||||
|
|
||||||
GITHUB_URL_REGEX = %r{^https?://(www\.)?github\.com/(?<user>[\w-]+)/(?<repo>[\w.-]+?)(\.git)?(/)?$}
|
GITHUB_URL_REGEX = %r{^https?://(www\.)?github\.com/(?<user>[\w-]+)/(?<repo>[\w.-]+?)(\.git)?(/)?$}.freeze
|
||||||
GITHUB_URL_WITH_TREE_REGEX = %r{^https?://(www\.)?github\.com/(?<user>[\w-]+)/(?<repo>[\w.-]+)/tree/(?<commit>[\w\.]+)(/)?$}
|
GITHUB_URL_WITH_TREE_REGEX = %r{^https?://(www\.)?github\.com/(?<user>[\w-]+)/(?<repo>[\w.-]+)/tree/(?<commit>[\w\.]+)(/)?$}.freeze
|
||||||
BITBUCKET_URL_REGEX = %r{^https?://(www\.)?bitbucket\.org/(?<user>[\w-]+)/(?<repo>[\w-]+)(\.git)?(/)?$}
|
BITBUCKET_URL_REGEX = %r{^https?://(www\.)?bitbucket\.org/(?<user>[\w-]+)/(?<repo>[\w-]+)(\.git)?(/)?$}.freeze
|
||||||
BITBUCKET_URL_BRANCH_REGEX = %r{^https?://(www\.)?bitbucket\.org/(?<user>[\w-]+)/(?<repo>[\w-]+)/branch/(?<branch>[\w\.]+)(/)?$}
|
BITBUCKET_URL_BRANCH_REGEX = %r{^https?://(www\.)?bitbucket\.org/(?<user>[\w-]+)/(?<repo>[\w-]+)/branch/(?<branch>[\w\.]+)(/)?$}.freeze
|
||||||
BITBUCKET_URL_COMMIT_REGEX = %r{^https?://(www\.)?bitbucket\.org/(?<user>[\w-]+)/(?<repo>[\w-]+)/commits/(?<commit>[\w\.]+)(/)?$}
|
BITBUCKET_URL_COMMIT_REGEX = %r{^https?://(www\.)?bitbucket\.org/(?<user>[\w-]+)/(?<repo>[\w-]+)/commits/(?<commit>[\w\.]+)(/)?$}.freeze
|
||||||
|
|
||||||
def self.transform(target)
|
def self.transform(target)
|
||||||
transformed_target = if m = GITHUB_URL_REGEX.match(target) # rubocop:disable Lint/AssignmentInCondition
|
transformed_target = if m = GITHUB_URL_REGEX.match(target) # rubocop:disable Lint/AssignmentInCondition
|
||||||
|
@ -94,8 +94,8 @@ module Fetchers
|
||||||
def initialize(url, opts)
|
def initialize(url, opts)
|
||||||
@target = url.to_s
|
@target = url.to_s
|
||||||
@target_uri = url.is_a?(URI) ? url : parse_uri(url)
|
@target_uri = url.is_a?(URI) ? url : parse_uri(url)
|
||||||
@insecure = opts['insecure']
|
@insecure = opts["insecure"]
|
||||||
@token = opts['token']
|
@token = opts["token"]
|
||||||
@config = opts
|
@config = opts
|
||||||
@archive_path = nil
|
@archive_path = nil
|
||||||
@temp_archive_path = nil
|
@temp_archive_path = nil
|
||||||
|
@ -126,23 +126,23 @@ module Fetchers
|
||||||
|
|
||||||
def sha256
|
def sha256
|
||||||
file = @archive_path || temp_archive_path
|
file = @archive_path || temp_archive_path
|
||||||
OpenSSL::Digest::SHA256.digest(File.read(file)).unpack('H*')[0]
|
OpenSSL::Digest::SHA256.digest(File.read(file)).unpack("H*")[0]
|
||||||
end
|
end
|
||||||
|
|
||||||
def file_type_from_remote(remote)
|
def file_type_from_remote(remote)
|
||||||
content_type = remote.meta['content-type']
|
content_type = remote.meta["content-type"]
|
||||||
file_type = MIME_TYPES[content_type]
|
file_type = MIME_TYPES[content_type]
|
||||||
|
|
||||||
if file_type.nil?
|
if file_type.nil?
|
||||||
Inspec::Log.warn("Unrecognized content type: #{content_type}. Assuming tar.gz")
|
Inspec::Log.warn("Unrecognized content type: #{content_type}. Assuming tar.gz")
|
||||||
file_type = '.tar.gz'
|
file_type = ".tar.gz"
|
||||||
end
|
end
|
||||||
|
|
||||||
file_type
|
file_type
|
||||||
end
|
end
|
||||||
|
|
||||||
def temp_archive_path
|
def temp_archive_path
|
||||||
@temp_archive_path ||= if @config['server_type'] == 'automate2'
|
@temp_archive_path ||= if @config["server_type"] == "automate2"
|
||||||
download_automate2_archive_to_temp
|
download_automate2_archive_to_temp
|
||||||
else
|
else
|
||||||
download_archive_to_temp
|
download_archive_to_temp
|
||||||
|
@ -154,13 +154,13 @@ module Fetchers
|
||||||
|
|
||||||
Inspec::Log.debug("Fetching URL: #{@target}")
|
Inspec::Log.debug("Fetching URL: #{@target}")
|
||||||
json = {
|
json = {
|
||||||
owner: @config['profile'][0],
|
owner: @config["profile"][0],
|
||||||
name: @config['profile'][1],
|
name: @config["profile"][1],
|
||||||
version: @config['profile'][2],
|
version: @config["profile"][2],
|
||||||
}.to_json
|
}.to_json
|
||||||
|
|
||||||
opts = http_opts
|
opts = http_opts
|
||||||
opts[:use_ssl] = @target_uri.scheme == 'https'
|
opts[:use_ssl] = @target_uri.scheme == "https"
|
||||||
|
|
||||||
if @insecure
|
if @insecure
|
||||||
opts[:verify_mode] = OpenSSL::SSL::VERIFY_NONE
|
opts[:verify_mode] = OpenSSL::SSL::VERIFY_NONE
|
||||||
|
@ -173,12 +173,12 @@ module Fetchers
|
||||||
req.add_field(key, value)
|
req.add_field(key, value)
|
||||||
end
|
end
|
||||||
req.body = json
|
req.body = json
|
||||||
res = Net::HTTP.start(@target_uri.host, @target_uri.port, opts) { |http|
|
res = Net::HTTP.start(@target_uri.host, @target_uri.port, opts) do |http|
|
||||||
http.request(req)
|
http.request(req)
|
||||||
}
|
end
|
||||||
|
|
||||||
@archive_type = '.tar.gz'
|
@archive_type = ".tar.gz"
|
||||||
archive = Tempfile.new(['inspec-dl-', @archive_type])
|
archive = Tempfile.new(["inspec-dl-", @archive_type])
|
||||||
archive.binmode
|
archive.binmode
|
||||||
archive.write(res.body)
|
archive.write(res.body)
|
||||||
archive.rewind
|
archive.rewind
|
||||||
|
@ -193,7 +193,7 @@ module Fetchers
|
||||||
Inspec::Log.debug("Fetching URL: #{@target}")
|
Inspec::Log.debug("Fetching URL: #{@target}")
|
||||||
remote = open_via_uri(@target)
|
remote = open_via_uri(@target)
|
||||||
@archive_type = file_type_from_remote(remote) # side effect :(
|
@archive_type = file_type_from_remote(remote) # side effect :(
|
||||||
archive = Tempfile.new(['inspec-dl-', @archive_type])
|
archive = Tempfile.new(["inspec-dl-", @archive_type])
|
||||||
archive.binmode
|
archive.binmode
|
||||||
archive.write(remote.read)
|
archive.write(remote.read)
|
||||||
archive.rewind
|
archive.rewind
|
||||||
|
@ -207,7 +207,7 @@ module Fetchers
|
||||||
|
|
||||||
if opts[:http_basic_authentication]
|
if opts[:http_basic_authentication]
|
||||||
# OpenURI does not support userinfo so we need to remove it
|
# OpenURI does not support userinfo so we need to remove it
|
||||||
open(target.sub("#{@target_uri.userinfo}@", ''), opts)
|
open(target.sub("#{@target_uri.userinfo}@", ""), opts)
|
||||||
else
|
else
|
||||||
open(target, opts)
|
open(target, opts)
|
||||||
end
|
end
|
||||||
|
@ -227,16 +227,16 @@ module Fetchers
|
||||||
opts = {}
|
opts = {}
|
||||||
opts[:ssl_verify_mode] = OpenSSL::SSL::VERIFY_NONE if @insecure
|
opts[:ssl_verify_mode] = OpenSSL::SSL::VERIFY_NONE if @insecure
|
||||||
|
|
||||||
if @config['server_type'] =~ /automate/
|
if @config["server_type"] =~ /automate/
|
||||||
opts['chef-delivery-enterprise'] = @config['automate']['ent']
|
opts["chef-delivery-enterprise"] = @config["automate"]["ent"]
|
||||||
if @config['automate']['token_type'] == 'dctoken'
|
if @config["automate"]["token_type"] == "dctoken"
|
||||||
opts['x-data-collector-token'] = @config['token']
|
opts["x-data-collector-token"] = @config["token"]
|
||||||
else
|
else
|
||||||
opts['chef-delivery-user'] = @config['user']
|
opts["chef-delivery-user"] = @config["user"]
|
||||||
opts['chef-delivery-token'] = @config['token']
|
opts["chef-delivery-token"] = @config["token"]
|
||||||
end
|
end
|
||||||
elsif @token
|
elsif @token
|
||||||
opts['Authorization'] = "Bearer #{@token}"
|
opts["Authorization"] = "Bearer #{@token}"
|
||||||
end
|
end
|
||||||
|
|
||||||
username = @config[:username] || @target_uri.user
|
username = @config[:username] || @target_uri.user
|
||||||
|
@ -260,8 +260,10 @@ module Fetchers
|
||||||
true
|
true
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
raise 'Unable to fetch profile - the following HTTP headers have no value: ' \
|
unless keys_missing_values.empty?
|
||||||
"#{keys_missing_values.join(', ')}" unless keys_missing_values.empty?
|
raise "Unable to fetch profile - the following HTTP headers have no value: " \
|
||||||
|
"#{keys_missing_values.join(', ')}"
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -3,29 +3,29 @@
|
||||||
libdir = File.dirname(__FILE__)
|
libdir = File.dirname(__FILE__)
|
||||||
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
|
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
|
||||||
|
|
||||||
require 'inspec/version'
|
require "inspec/version"
|
||||||
require 'inspec/exceptions'
|
require "inspec/exceptions"
|
||||||
require 'inspec/utils/deprecation'
|
require "inspec/utils/deprecation"
|
||||||
require 'inspec/profile'
|
require "inspec/profile"
|
||||||
require 'inspec/rule'
|
require "inspec/rule"
|
||||||
require 'matchers/matchers'
|
require "matchers/matchers"
|
||||||
require 'inspec/runner'
|
require "inspec/runner"
|
||||||
require 'inspec/shell'
|
require "inspec/shell"
|
||||||
require 'inspec/formatters'
|
require "inspec/formatters"
|
||||||
require 'inspec/reporters'
|
require "inspec/reporters"
|
||||||
require 'inspec/input_registry'
|
require "inspec/input_registry"
|
||||||
require 'inspec/rspec_extensions'
|
require "inspec/rspec_extensions"
|
||||||
require 'inspec/globals'
|
require "inspec/globals"
|
||||||
require 'inspec/impact'
|
require "inspec/impact"
|
||||||
require 'inspec/utils/telemetry'
|
require "inspec/utils/telemetry"
|
||||||
require 'inspec/utils/telemetry/global_methods'
|
require "inspec/utils/telemetry/global_methods"
|
||||||
|
|
||||||
require 'inspec/plugin/v2'
|
require "inspec/plugin/v2"
|
||||||
require 'inspec/plugin/v1'
|
require "inspec/plugin/v1"
|
||||||
|
|
||||||
# all utils that may be required by legacy plugins
|
# all utils that may be required by legacy plugins
|
||||||
require 'inspec/base_cli'
|
require "inspec/base_cli"
|
||||||
require 'inspec/fetcher'
|
require "inspec/fetcher"
|
||||||
require 'inspec/source_reader'
|
require "inspec/source_reader"
|
||||||
require 'inspec/resource'
|
require "inspec/resource"
|
||||||
require 'inspec/resources'
|
require "inspec/resources"
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
require 'rubygems/package'
|
require "rubygems/package"
|
||||||
|
|
||||||
module Inspec::Archive
|
module Inspec::Archive
|
||||||
class TarArchiveGenerator
|
class TarArchiveGenerator
|
||||||
def archive(base_dir, files, archive)
|
def archive(base_dir, files, archive)
|
||||||
File.open(archive, 'wb') do |file|
|
File.open(archive, "wb") do |file|
|
||||||
Zlib::GzipWriter.wrap(file) do |gz|
|
Zlib::GzipWriter.wrap(file) do |gz|
|
||||||
Gem::Package::TarWriter.new(gz) do |tar|
|
Gem::Package::TarWriter.new(gz) do |tar|
|
||||||
files.each do |input_filename|
|
files.each do |input_filename|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
require 'rubygems'
|
require "rubygems"
|
||||||
require 'zip'
|
require "zip"
|
||||||
require 'pathname'
|
require "pathname"
|
||||||
|
|
||||||
module Inspec::Archive
|
module Inspec::Archive
|
||||||
class ZipArchiveGenerator
|
class ZipArchiveGenerator
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# copyright: 2015, Dominik Richter
|
# copyright: 2015, Dominik Richter
|
||||||
|
|
||||||
require 'train'
|
require "train"
|
||||||
require 'inspec/config'
|
require "inspec/config"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
module Backend
|
module Backend
|
||||||
|
@ -25,7 +25,7 @@ module Inspec
|
||||||
|
|
||||||
# Ruby internal for printing a nice name for this class
|
# Ruby internal for printing a nice name for this class
|
||||||
def to_s
|
def to_s
|
||||||
'Inspec::Backend::Class'
|
"Inspec::Backend::Class"
|
||||||
end
|
end
|
||||||
|
|
||||||
# Ruby internal for pretty-printing a summary for this class
|
# Ruby internal for pretty-printing a summary for this class
|
||||||
|
@ -54,15 +54,15 @@ module Inspec
|
||||||
# Set caching settings. We always want to enable caching for
|
# Set caching settings. We always want to enable caching for
|
||||||
# the Mock transport for testing.
|
# the Mock transport for testing.
|
||||||
if config[:backend_cache] || config[:backend] == :mock
|
if config[:backend_cache] || config[:backend] == :mock
|
||||||
Inspec::Log.debug 'Option backend_cache is enabled'
|
Inspec::Log.debug "Option backend_cache is enabled"
|
||||||
connection.enable_cache(:file)
|
connection.enable_cache(:file)
|
||||||
connection.enable_cache(:command)
|
connection.enable_cache(:command)
|
||||||
elsif config[:debug_shell]
|
elsif config[:debug_shell]
|
||||||
Inspec::Log.debug 'Option backend_cache is disabled'
|
Inspec::Log.debug "Option backend_cache is disabled"
|
||||||
connection.disable_cache(:file)
|
connection.disable_cache(:file)
|
||||||
connection.disable_cache(:command)
|
connection.disable_cache(:command)
|
||||||
else
|
else
|
||||||
Inspec::Log.debug 'Option backend_cache is disabled'
|
Inspec::Log.debug "Option backend_cache is disabled"
|
||||||
connection.disable_cache(:file)
|
connection.disable_cache(:file)
|
||||||
connection.disable_cache(:command)
|
connection.disable_cache(:command)
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
require 'thor'
|
require "thor"
|
||||||
require 'inspec/log'
|
require "inspec/log"
|
||||||
require 'inspec/profile_vendor'
|
require "inspec/profile_vendor"
|
||||||
require 'inspec/ui'
|
require "inspec/ui"
|
||||||
|
|
||||||
# Allow end of options during array type parsing
|
# Allow end of options during array type parsing
|
||||||
# https://github.com/erikhuda/thor/issues/631
|
# https://github.com/erikhuda/thor/issues/631
|
||||||
|
@ -30,107 +30,107 @@ module Inspec
|
||||||
|
|
||||||
def self.target_options # rubocop:disable MethodLength
|
def self.target_options # rubocop:disable MethodLength
|
||||||
option :target, aliases: :t, type: :string,
|
option :target, aliases: :t, type: :string,
|
||||||
desc: 'Simple targeting option using URIs, e.g. ssh://user:pass@host:port'
|
desc: "Simple targeting option using URIs, e.g. ssh://user:pass@host:port"
|
||||||
option :backend, aliases: :b, type: :string,
|
option :backend, aliases: :b, type: :string,
|
||||||
desc: 'Choose a backend: local, ssh, winrm, docker.'
|
desc: "Choose a backend: local, ssh, winrm, docker."
|
||||||
option :host, type: :string,
|
option :host, type: :string,
|
||||||
desc: 'Specify a remote host which is tested.'
|
desc: "Specify a remote host which is tested."
|
||||||
option :port, aliases: :p, type: :numeric,
|
option :port, aliases: :p, type: :numeric,
|
||||||
desc: 'Specify the login port for a remote scan.'
|
desc: "Specify the login port for a remote scan."
|
||||||
option :user, type: :string,
|
option :user, type: :string,
|
||||||
desc: 'The login user for a remote scan.'
|
desc: "The login user for a remote scan."
|
||||||
option :password, type: :string, lazy_default: -1,
|
option :password, type: :string, lazy_default: -1,
|
||||||
desc: 'Login password for a remote scan, if required.'
|
desc: "Login password for a remote scan, if required."
|
||||||
option :enable_password, type: :string, lazy_default: -1,
|
option :enable_password, type: :string, lazy_default: -1,
|
||||||
desc: 'Password for enable mode on Cisco IOS devices.'
|
desc: "Password for enable mode on Cisco IOS devices."
|
||||||
option :key_files, aliases: :i, type: :array,
|
option :key_files, aliases: :i, type: :array,
|
||||||
desc: 'Login key or certificate file for a remote scan.'
|
desc: "Login key or certificate file for a remote scan."
|
||||||
option :path, type: :string,
|
option :path, type: :string,
|
||||||
desc: 'Login path to use when connecting to the target (WinRM).'
|
desc: "Login path to use when connecting to the target (WinRM)."
|
||||||
option :sudo, type: :boolean,
|
option :sudo, type: :boolean,
|
||||||
desc: 'Run scans with sudo. Only activates on Unix and non-root user.'
|
desc: "Run scans with sudo. Only activates on Unix and non-root user."
|
||||||
option :sudo_password, type: :string, lazy_default: -1,
|
option :sudo_password, type: :string, lazy_default: -1,
|
||||||
desc: 'Specify a sudo password, if it is required.'
|
desc: "Specify a sudo password, if it is required."
|
||||||
option :sudo_options, type: :string,
|
option :sudo_options, type: :string,
|
||||||
desc: 'Additional sudo options for a remote scan.'
|
desc: "Additional sudo options for a remote scan."
|
||||||
option :sudo_command, type: :string,
|
option :sudo_command, type: :string,
|
||||||
desc: 'Alternate command for sudo.'
|
desc: "Alternate command for sudo."
|
||||||
option :shell, type: :boolean,
|
option :shell, type: :boolean,
|
||||||
desc: 'Run scans in a subshell. Only activates on Unix.'
|
desc: "Run scans in a subshell. Only activates on Unix."
|
||||||
option :shell_options, type: :string,
|
option :shell_options, type: :string,
|
||||||
desc: 'Additional shell options.'
|
desc: "Additional shell options."
|
||||||
option :shell_command, type: :string,
|
option :shell_command, type: :string,
|
||||||
desc: 'Specify a particular shell to use.'
|
desc: "Specify a particular shell to use."
|
||||||
option :ssl, type: :boolean,
|
option :ssl, type: :boolean,
|
||||||
desc: 'Use SSL for transport layer encryption (WinRM).'
|
desc: "Use SSL for transport layer encryption (WinRM)."
|
||||||
option :self_signed, type: :boolean,
|
option :self_signed, type: :boolean,
|
||||||
desc: 'Allow remote scans with self-signed certificates (WinRM).'
|
desc: "Allow remote scans with self-signed certificates (WinRM)."
|
||||||
option :winrm_transport, type: :string, default: 'negotiate',
|
option :winrm_transport, type: :string, default: "negotiate",
|
||||||
desc: 'Specify which transport to use, defaults to negotiate (WinRM).'
|
desc: "Specify which transport to use, defaults to negotiate (WinRM)."
|
||||||
option :winrm_disable_sspi, type: :boolean,
|
option :winrm_disable_sspi, type: :boolean,
|
||||||
desc: 'Whether to use disable sspi authentication, defaults to false (WinRM).'
|
desc: "Whether to use disable sspi authentication, defaults to false (WinRM)."
|
||||||
option :winrm_basic_auth, type: :boolean,
|
option :winrm_basic_auth, type: :boolean,
|
||||||
desc: 'Whether to use basic authentication, defaults to false (WinRM).'
|
desc: "Whether to use basic authentication, defaults to false (WinRM)."
|
||||||
option :config, type: :string,
|
option :config, type: :string,
|
||||||
desc: 'Read configuration from JSON file (`-` reads from stdin).'
|
desc: "Read configuration from JSON file (`-` reads from stdin)."
|
||||||
option :json_config, type: :string, hide: true
|
option :json_config, type: :string, hide: true
|
||||||
option :proxy_command, type: :string,
|
option :proxy_command, type: :string,
|
||||||
desc: 'Specifies the command to use to connect to the server'
|
desc: "Specifies the command to use to connect to the server"
|
||||||
option :bastion_host, type: :string,
|
option :bastion_host, type: :string,
|
||||||
desc: 'Specifies the bastion host if applicable'
|
desc: "Specifies the bastion host if applicable"
|
||||||
option :bastion_user, type: :string,
|
option :bastion_user, type: :string,
|
||||||
desc: 'Specifies the bastion user if applicable'
|
desc: "Specifies the bastion user if applicable"
|
||||||
option :bastion_port, type: :string,
|
option :bastion_port, type: :string,
|
||||||
desc: 'Specifies the bastion port if applicable'
|
desc: "Specifies the bastion port if applicable"
|
||||||
option :insecure, type: :boolean, default: false,
|
option :insecure, type: :boolean, default: false,
|
||||||
desc: 'Disable SSL verification on select targets'
|
desc: "Disable SSL verification on select targets"
|
||||||
option :target_id, type: :string,
|
option :target_id, type: :string,
|
||||||
desc: 'Provide a ID which will be included on reports'
|
desc: "Provide a ID which will be included on reports"
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.profile_options
|
def self.profile_options
|
||||||
option :profiles_path, type: :string,
|
option :profiles_path, type: :string,
|
||||||
desc: 'Folder which contains referenced profiles.'
|
desc: "Folder which contains referenced profiles."
|
||||||
option :vendor_cache, type: :string,
|
option :vendor_cache, type: :string,
|
||||||
desc: 'Use the given path for caching dependencies. (default: ~/.inspec/cache)'
|
desc: "Use the given path for caching dependencies. (default: ~/.inspec/cache)"
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.exec_options
|
def self.exec_options
|
||||||
target_options
|
target_options
|
||||||
profile_options
|
profile_options
|
||||||
option :controls, type: :array,
|
option :controls, type: :array,
|
||||||
desc: 'A list of control names to run, or a list of /regexes/ to match against control names. Ignore all other tests.'
|
desc: "A list of control names to run, or a list of /regexes/ to match against control names. Ignore all other tests."
|
||||||
option :reporter, type: :array,
|
option :reporter, type: :array,
|
||||||
banner: 'one two:/output/file/path',
|
banner: "one two:/output/file/path",
|
||||||
desc: 'Enable one or more output reporters: cli, documentation, html, progress, json, json-min, json-rspec, junit, yaml'
|
desc: "Enable one or more output reporters: cli, documentation, html, progress, json, json-min, json-rspec, junit, yaml"
|
||||||
option :input_file, type: :array,
|
option :input_file, type: :array,
|
||||||
desc: 'Load one or more input files, a YAML file with values for the profile to use'
|
desc: "Load one or more input files, a YAML file with values for the profile to use"
|
||||||
option :attrs, type: :array,
|
option :attrs, type: :array,
|
||||||
desc: 'Legacy name for --input-file - deprecated.'
|
desc: "Legacy name for --input-file - deprecated."
|
||||||
option :create_lockfile, type: :boolean,
|
option :create_lockfile, type: :boolean,
|
||||||
desc: 'Write out a lockfile based on this execution (unless one already exists)'
|
desc: "Write out a lockfile based on this execution (unless one already exists)"
|
||||||
option :backend_cache, type: :boolean,
|
option :backend_cache, type: :boolean,
|
||||||
desc: 'Allow caching for backend command output. (default: true)'
|
desc: "Allow caching for backend command output. (default: true)"
|
||||||
option :show_progress, type: :boolean,
|
option :show_progress, type: :boolean,
|
||||||
desc: 'Show progress while executing tests.'
|
desc: "Show progress while executing tests."
|
||||||
option :distinct_exit, type: :boolean, default: true,
|
option :distinct_exit, type: :boolean, default: true,
|
||||||
desc: 'Exit with code 101 if any tests fail, and 100 if any are skipped (default). If disabled, exit 0 on skips and 1 for failures.'
|
desc: "Exit with code 101 if any tests fail, and 100 if any are skipped (default). If disabled, exit 0 on skips and 1 for failures."
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.format_platform_info(params: {}, indent: 0, color: 39)
|
def self.format_platform_info(params: {}, indent: 0, color: 39)
|
||||||
str = ''
|
str = ""
|
||||||
params.each { |item, info|
|
params.each do |item, info|
|
||||||
data = info
|
data = info
|
||||||
|
|
||||||
# Format Array for better output if applicable
|
# Format Array for better output if applicable
|
||||||
data = data.join(', ') if data.is_a?(Array)
|
data = data.join(", ") if data.is_a?(Array)
|
||||||
|
|
||||||
# Do not output fields of data is missing ('unknown' is fine)
|
# Do not output fields of data is missing ('unknown' is fine)
|
||||||
next if data.nil?
|
next if data.nil?
|
||||||
|
|
||||||
data = "\e[1m\e[#{color}m#{data}\e[0m"
|
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
|
str
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -189,12 +189,12 @@ module Inspec
|
||||||
private
|
private
|
||||||
|
|
||||||
def suppress_log_output?(opts)
|
def suppress_log_output?(opts)
|
||||||
return false if opts['reporter'].nil?
|
return false if opts["reporter"].nil?
|
||||||
match = %w{json json-min json-rspec json-automate junit html yaml documentation progress} & opts['reporter'].keys
|
match = %w{json json-min json-rspec json-automate junit html yaml documentation progress} & opts["reporter"].keys
|
||||||
unless match.empty?
|
unless match.empty?
|
||||||
match.each do |m|
|
match.each do |m|
|
||||||
# check to see if we are outputting to stdout
|
# check to see if we are outputting to stdout
|
||||||
return true if opts['reporter'][m]['stdout'] == true
|
return true if opts["reporter"][m]["stdout"] == true
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
false
|
false
|
||||||
|
@ -216,7 +216,7 @@ module Inspec
|
||||||
if valid.include?(level)
|
if valid.include?(level)
|
||||||
l = level
|
l = level
|
||||||
else
|
else
|
||||||
l = 'info'
|
l = "info"
|
||||||
end
|
end
|
||||||
|
|
||||||
Logger.const_get(l.upcase)
|
Logger.const_get(l.upcase)
|
||||||
|
@ -237,7 +237,7 @@ module Inspec
|
||||||
profile_vendor = Inspec::ProfileVendor.new(profile_path)
|
profile_vendor = Inspec::ProfileVendor.new(profile_path)
|
||||||
|
|
||||||
if (profile_vendor.cache_path.exist? || profile_vendor.lockfile.exist?) && !opts[:overwrite]
|
if (profile_vendor.cache_path.exist? || profile_vendor.lockfile.exist?) && !opts[:overwrite]
|
||||||
puts 'Profile is already vendored. Use --overwrite.'
|
puts "Profile is already vendored. Use --overwrite."
|
||||||
return false
|
return false
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -253,8 +253,8 @@ module Inspec
|
||||||
# logging singleton Inspec::Log. Eventually it would be nice to
|
# logging singleton Inspec::Log. Eventually it would be nice to
|
||||||
# move internal debug logging to use this logging singleton.
|
# move internal debug logging to use this logging singleton.
|
||||||
#
|
#
|
||||||
loc = if o['log_location']
|
loc = if o["log_location"]
|
||||||
o['log_location']
|
o["log_location"]
|
||||||
elsif suppress_log_output?(o)
|
elsif suppress_log_output?(o)
|
||||||
$stderr
|
$stderr
|
||||||
else
|
else
|
||||||
|
@ -262,14 +262,14 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
Inspec::Log.init(loc)
|
Inspec::Log.init(loc)
|
||||||
Inspec::Log.level = get_log_level(o['log_level'])
|
Inspec::Log.level = get_log_level(o["log_level"])
|
||||||
|
|
||||||
o[:logger] = Logger.new(loc)
|
o[:logger] = Logger.new(loc)
|
||||||
# output json if we have activated the json formatter
|
# output json if we have activated the json formatter
|
||||||
if o['log-format'] == 'json'
|
if o["log-format"] == "json"
|
||||||
o[:logger].formatter = Logger::JSONFormatter.new
|
o[:logger].formatter = Logger::JSONFormatter.new
|
||||||
end
|
end
|
||||||
o[:logger].level = get_log_level(o['log_level'])
|
o[:logger].level = get_log_level(o["log_level"])
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
require 'inspec/fetcher'
|
require "inspec/fetcher"
|
||||||
require 'forwardable'
|
require "forwardable"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
class CachedFetcher
|
class CachedFetcher
|
||||||
|
|
|
@ -1,58 +1,58 @@
|
||||||
# Copyright 2015 Dominik Richter
|
# Copyright 2015 Dominik Richter
|
||||||
|
|
||||||
require 'logger'
|
require "logger"
|
||||||
require 'thor'
|
require "thor"
|
||||||
require 'json'
|
require "json"
|
||||||
require 'pp'
|
require "pp"
|
||||||
require 'inspec/utils/json_log'
|
require "inspec/utils/json_log"
|
||||||
require 'inspec/utils/latest_version'
|
require "inspec/utils/latest_version"
|
||||||
require 'inspec/base_cli'
|
require "inspec/base_cli"
|
||||||
require 'inspec/plugin/v1'
|
require "inspec/plugin/v1"
|
||||||
require 'inspec/plugin/v2'
|
require "inspec/plugin/v2"
|
||||||
require 'inspec/runner_mock'
|
require "inspec/runner_mock"
|
||||||
require 'inspec/env_printer'
|
require "inspec/env_printer"
|
||||||
require 'inspec/schema'
|
require "inspec/schema"
|
||||||
require 'inspec/config'
|
require "inspec/config"
|
||||||
require 'inspec/dist'
|
require "inspec/dist"
|
||||||
|
|
||||||
class Inspec::InspecCLI < Inspec::BaseCLI
|
class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
class_option :log_level, aliases: :l, type: :string,
|
class_option :log_level, aliases: :l, type: :string,
|
||||||
desc: 'Set the log level: info (default), debug, warn, error'
|
desc: "Set the log level: info (default), debug, warn, error"
|
||||||
|
|
||||||
class_option :log_location, type: :string,
|
class_option :log_location, type: :string,
|
||||||
desc: 'Location to send diagnostic log messages to. (default: $stdout or Inspec::Log.error)'
|
desc: "Location to send diagnostic log messages to. (default: $stdout or Inspec::Log.error)"
|
||||||
|
|
||||||
class_option :diagnose, type: :boolean,
|
class_option :diagnose, type: :boolean,
|
||||||
desc: 'Show diagnostics (versions, configurations)'
|
desc: "Show diagnostics (versions, configurations)"
|
||||||
|
|
||||||
class_option :color, type: :boolean,
|
class_option :color, type: :boolean,
|
||||||
desc: 'Use colors in output.'
|
desc: "Use colors in output."
|
||||||
|
|
||||||
class_option :interactive, type: :boolean,
|
class_option :interactive, type: :boolean,
|
||||||
desc: 'Allow or disable user interaction'
|
desc: "Allow or disable user interaction"
|
||||||
|
|
||||||
class_option :disable_core_plugins, type: :string, banner: '', # Actually a boolean, but this suppresses the creation of a --no-disable...
|
class_option :disable_core_plugins, type: :string, banner: "", # Actually a boolean, but this suppresses the creation of a --no-disable...
|
||||||
desc: 'Disable loading all plugins that are shipped in the lib/plugins directory of InSpec. Useful in development.'
|
desc: "Disable loading all plugins that are shipped in the lib/plugins directory of InSpec. Useful in development."
|
||||||
|
|
||||||
class_option :disable_user_plugins, type: :string, banner: '',
|
class_option :disable_user_plugins, type: :string, banner: "",
|
||||||
desc: 'Disable loading all plugins that the user installed.'
|
desc: "Disable loading all plugins that the user installed."
|
||||||
|
|
||||||
class_option :enable_telemetry, type: :boolean,
|
class_option :enable_telemetry, type: :boolean,
|
||||||
desc: 'Allow or disable telemetry', default: false
|
desc: "Allow or disable telemetry", default: false
|
||||||
|
|
||||||
require 'license_acceptance/cli_flags/thor'
|
require "license_acceptance/cli_flags/thor"
|
||||||
include LicenseAcceptance::CLIFlags::Thor
|
include LicenseAcceptance::CLIFlags::Thor
|
||||||
|
|
||||||
desc 'json PATH', 'read all tests in PATH and generate a JSON summary'
|
desc "json PATH", "read all tests in PATH and generate a JSON summary"
|
||||||
option :output, aliases: :o, type: :string,
|
option :output, aliases: :o, type: :string,
|
||||||
desc: 'Save the created profile to a path'
|
desc: "Save the created profile to a path"
|
||||||
option :controls, type: :array,
|
option :controls, type: :array,
|
||||||
desc: 'A list of controls to include. Ignore all other tests.'
|
desc: "A list of controls to include. Ignore all other tests."
|
||||||
profile_options
|
profile_options
|
||||||
def json(target)
|
def json(target)
|
||||||
o = config
|
o = config
|
||||||
diagnose(o)
|
diagnose(o)
|
||||||
o['log_location'] = $stderr
|
o["log_location"] = $stderr
|
||||||
configure_logger(o)
|
configure_logger(o)
|
||||||
|
|
||||||
o[:backend] = Inspec::Backend.create(Inspec::Config.mock)
|
o[:backend] = Inspec::Backend.create(Inspec::Config.mock)
|
||||||
|
@ -63,7 +63,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
info = profile.info
|
info = profile.info
|
||||||
# add in inspec version
|
# add in inspec version
|
||||||
info[:generator] = {
|
info[:generator] = {
|
||||||
name: 'inspec',
|
name: "inspec",
|
||||||
version: Inspec::VERSION,
|
version: Inspec::VERSION,
|
||||||
}
|
}
|
||||||
dst = o[:output].to_s
|
dst = o[:output].to_s
|
||||||
|
@ -82,14 +82,14 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
pretty_handle_exception(e)
|
pretty_handle_exception(e)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'check PATH', 'verify all tests at the specified PATH'
|
desc "check PATH", "verify all tests at the specified PATH"
|
||||||
option :format, type: :string
|
option :format, type: :string
|
||||||
profile_options
|
profile_options
|
||||||
def check(path) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength
|
def check(path) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength
|
||||||
o = config
|
o = config
|
||||||
diagnose(o)
|
diagnose(o)
|
||||||
o['log_location'] ||= STDERR if o['format'] == 'json'
|
o["log_location"] ||= STDERR if o["format"] == "json"
|
||||||
o['log_level'] ||= 'warn'
|
o["log_level"] ||= "warn"
|
||||||
configure_logger(o)
|
configure_logger(o)
|
||||||
|
|
||||||
o[:backend] = Inspec::Backend.create(Inspec::Config.mock)
|
o[:backend] = Inspec::Backend.create(Inspec::Config.mock)
|
||||||
|
@ -100,25 +100,25 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
profile = Inspec::Profile.for_target(path, o)
|
profile = Inspec::Profile.for_target(path, o)
|
||||||
result = profile.check
|
result = profile.check
|
||||||
|
|
||||||
if o['format'] == 'json'
|
if o["format"] == "json"
|
||||||
puts JSON.generate(result)
|
puts JSON.generate(result)
|
||||||
else
|
else
|
||||||
%w{location profile controls timestamp valid}.each do |item|
|
%w{location profile controls timestamp valid}.each do |item|
|
||||||
puts format('%-12s %s', item.to_s.capitalize + ':',
|
puts format("%-12s %s", item.to_s.capitalize + ":",
|
||||||
mark_text(result[:summary][item.to_sym]))
|
mark_text(result[:summary][item.to_sym]))
|
||||||
end
|
end
|
||||||
puts
|
puts
|
||||||
|
|
||||||
if result[:errors].empty? and result[:warnings].empty?
|
if result[:errors].empty? && result[:warnings].empty?
|
||||||
puts 'No errors or warnings'
|
puts "No errors or warnings"
|
||||||
else
|
else
|
||||||
red = "\033[31m"
|
red = "\033[31m"
|
||||||
yellow = "\033[33m"
|
yellow = "\033[33m"
|
||||||
rst = "\033[0m"
|
rst = "\033[0m"
|
||||||
|
|
||||||
item_msg = lambda { |item|
|
item_msg = lambda { |item|
|
||||||
pos = [item[:file], item[:line], item[:column]].compact.join(':')
|
pos = [item[:file], item[:line], item[:column]].compact.join(":")
|
||||||
pos.empty? ? item[:msg] : pos + ': ' + item[:msg]
|
pos.empty? ? item[:msg] : pos + ": " + item[:msg]
|
||||||
}
|
}
|
||||||
result[:errors].each do |item|
|
result[:errors].each do |item|
|
||||||
puts "#{red} ✖ #{item_msg.call(item)}#{rst}"
|
puts "#{red} ✖ #{item_msg.call(item)}#{rst}"
|
||||||
|
@ -128,7 +128,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
end
|
end
|
||||||
|
|
||||||
puts
|
puts
|
||||||
puts format('Summary: %s%d errors%s, %s%d warnings%s',
|
puts format("Summary: %s%d errors%s, %s%d warnings%s",
|
||||||
red, result[:errors].length, rst,
|
red, result[:errors].length, rst,
|
||||||
yellow, result[:warnings].length, rst)
|
yellow, result[:warnings].length, rst)
|
||||||
end
|
end
|
||||||
|
@ -138,9 +138,9 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
pretty_handle_exception(e)
|
pretty_handle_exception(e)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'vendor PATH', 'Download all dependencies and generate a lockfile in a `vendor` directory'
|
desc "vendor PATH", "Download all dependencies and generate a lockfile in a `vendor` directory"
|
||||||
option :overwrite, type: :boolean, default: false,
|
option :overwrite, type: :boolean, default: false,
|
||||||
desc: 'Overwrite existing vendored dependencies and lockfile.'
|
desc: "Overwrite existing vendored dependencies and lockfile."
|
||||||
def vendor(path = nil)
|
def vendor(path = nil)
|
||||||
o = config
|
o = config
|
||||||
configure_logger(o)
|
configure_logger(o)
|
||||||
|
@ -150,18 +150,18 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
vendor_deps(path, o)
|
vendor_deps(path, o)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'archive PATH', 'archive a profile to tar.gz (default) or zip'
|
desc "archive PATH", "archive a profile to tar.gz (default) or zip"
|
||||||
profile_options
|
profile_options
|
||||||
option :output, aliases: :o, type: :string,
|
option :output, aliases: :o, type: :string,
|
||||||
desc: 'Save the archive to a path'
|
desc: "Save the archive to a path"
|
||||||
option :zip, type: :boolean, default: false,
|
option :zip, type: :boolean, default: false,
|
||||||
desc: 'Generates a zip archive.'
|
desc: "Generates a zip archive."
|
||||||
option :tar, type: :boolean, default: false,
|
option :tar, type: :boolean, default: false,
|
||||||
desc: 'Generates a tar.gz archive.'
|
desc: "Generates a tar.gz archive."
|
||||||
option :overwrite, type: :boolean, default: false,
|
option :overwrite, type: :boolean, default: false,
|
||||||
desc: 'Overwrite existing archive.'
|
desc: "Overwrite existing archive."
|
||||||
option :ignore_errors, type: :boolean, default: false,
|
option :ignore_errors, type: :boolean, default: false,
|
||||||
desc: 'Ignore profile warnings.'
|
desc: "Ignore profile warnings."
|
||||||
def archive(path)
|
def archive(path)
|
||||||
o = config
|
o = config
|
||||||
diagnose(o)
|
diagnose(o)
|
||||||
|
@ -179,7 +179,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
result = profile.check
|
result = profile.check
|
||||||
|
|
||||||
if result && !o[:ignore_errors] == false
|
if result && !o[:ignore_errors] == false
|
||||||
o[:logger].info 'Profile check failed. Please fix the profile before generating an archive.'
|
o[:logger].info "Profile check failed. Please fix the profile before generating an archive."
|
||||||
return exit 1
|
return exit 1
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -189,7 +189,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
pretty_handle_exception(e)
|
pretty_handle_exception(e)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'exec LOCATIONS', 'run all test files at the specified LOCATIONS.'
|
desc "exec LOCATIONS", "run all test files at the specified LOCATIONS."
|
||||||
# TODO: find a way for Thor not to butcher the formatting of this
|
# TODO: find a way for Thor not to butcher the formatting of this
|
||||||
long_desc <<~EOT
|
long_desc <<~EOT
|
||||||
Loads the given profile(s) and fetches their dependencies if needed. Then
|
Loads the given profile(s) and fetches their dependencies if needed. Then
|
||||||
|
@ -279,17 +279,17 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
pretty_handle_exception(e)
|
pretty_handle_exception(e)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'detect', 'detect the target OS'
|
desc "detect", "detect the target OS"
|
||||||
target_options
|
target_options
|
||||||
option :format, type: :string
|
option :format, type: :string
|
||||||
def detect
|
def detect
|
||||||
o = config
|
o = config
|
||||||
o[:command] = 'platform.params'
|
o[:command] = "platform.params"
|
||||||
(_, res) = run_command(o)
|
(_, res) = run_command(o)
|
||||||
if o['format'] == 'json'
|
if o["format"] == "json"
|
||||||
puts res.to_json
|
puts res.to_json
|
||||||
else
|
else
|
||||||
headline('Platform Details')
|
headline("Platform Details")
|
||||||
puts Inspec::BaseCLI.format_platform_info(params: res, indent: 0, color: 36)
|
puts Inspec::BaseCLI.format_platform_info(params: res, indent: 0, color: 36)
|
||||||
end
|
end
|
||||||
rescue ArgumentError, RuntimeError, Train::UserError => e
|
rescue ArgumentError, RuntimeError, Train::UserError => e
|
||||||
|
@ -299,17 +299,17 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
pretty_handle_exception(e)
|
pretty_handle_exception(e)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'shell', 'open an interactive debugging shell'
|
desc "shell", "open an interactive debugging shell"
|
||||||
target_options
|
target_options
|
||||||
option :command, aliases: :c,
|
option :command, aliases: :c,
|
||||||
desc: 'A single command string to run instead of launching the shell'
|
desc: "A single command string to run instead of launching the shell"
|
||||||
option :reporter, type: :array,
|
option :reporter, type: :array,
|
||||||
banner: 'one two:/output/file/path',
|
banner: "one two:/output/file/path",
|
||||||
desc: 'Enable one or more output reporters: cli, documentation, html, progress, json, json-min, json-rspec, junit'
|
desc: "Enable one or more output reporters: cli, documentation, html, progress, json, json-min, json-rspec, junit"
|
||||||
option :depends, type: :array, default: [],
|
option :depends, type: :array, default: [],
|
||||||
desc: 'A space-delimited list of local folders containing profiles whose libraries and resources will be loaded into the new shell'
|
desc: "A space-delimited list of local folders containing profiles whose libraries and resources will be loaded into the new shell"
|
||||||
option :distinct_exit, type: :boolean, default: true,
|
option :distinct_exit, type: :boolean, default: true,
|
||||||
desc: 'Exit with code 100 if any tests fail, and 101 if any are skipped but none failed (default). If disabled, exit 0 on skips and 1 for failures.'
|
desc: "Exit with code 100 if any tests fail, and 101 if any are skipped but none failed (default). If disabled, exit 0 on skips and 1 for failures."
|
||||||
def shell_func
|
def shell_func
|
||||||
o = config
|
o = config
|
||||||
diagnose(o)
|
diagnose(o)
|
||||||
|
@ -328,7 +328,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
exit res unless run_type == :ruby_eval
|
exit res unless run_type == :ruby_eval
|
||||||
|
|
||||||
# No InSpec tests - just print evaluation output.
|
# No InSpec tests - just print evaluation output.
|
||||||
res = (res.respond_to?(:to_json) ? res.to_json : JSON.dump(res)) if o['reporter']&.keys&.include?('json')
|
res = (res.respond_to?(:to_json) ? res.to_json : JSON.dump(res)) if o["reporter"]&.keys&.include?("json")
|
||||||
puts res
|
puts res
|
||||||
exit 0
|
exit 0
|
||||||
rescue RuntimeError, Train::UserError => e
|
rescue RuntimeError, Train::UserError => e
|
||||||
|
@ -337,7 +337,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
pretty_handle_exception(e)
|
pretty_handle_exception(e)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'env', 'Output shell-appropriate completion configuration'
|
desc "env", "Output shell-appropriate completion configuration"
|
||||||
def env(shell = nil)
|
def env(shell = nil)
|
||||||
p = Inspec::EnvPrinter.new(self.class, shell)
|
p = Inspec::EnvPrinter.new(self.class, shell)
|
||||||
p.print_and_exit!
|
p.print_and_exit!
|
||||||
|
@ -345,7 +345,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
pretty_handle_exception(e)
|
pretty_handle_exception(e)
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'schema NAME', 'print the JSON schema', hide: true
|
desc "schema NAME", "print the JSON schema", hide: true
|
||||||
def schema(name)
|
def schema(name)
|
||||||
puts Inspec::Schema.json(name)
|
puts Inspec::Schema.json(name)
|
||||||
rescue StandardError => e
|
rescue StandardError => e
|
||||||
|
@ -353,10 +353,10 @@ class Inspec::InspecCLI < Inspec::BaseCLI
|
||||||
puts "Valid schemas are #{Inspec::Schema.names.join(', ')}"
|
puts "Valid schemas are #{Inspec::Schema.names.join(', ')}"
|
||||||
end
|
end
|
||||||
|
|
||||||
desc 'version', 'prints the version of this tool'
|
desc "version", "prints the version of this tool"
|
||||||
option :format, type: :string
|
option :format, type: :string
|
||||||
def version
|
def version
|
||||||
if config['format'] == 'json'
|
if config["format"] == "json"
|
||||||
v = { version: Inspec::VERSION }
|
v = { version: Inspec::VERSION }
|
||||||
puts v.to_json
|
puts v.to_json
|
||||||
else
|
else
|
||||||
|
@ -386,25 +386,25 @@ end
|
||||||
# Pre-Flight Code
|
# Pre-Flight Code
|
||||||
#=====================================================================#
|
#=====================================================================#
|
||||||
|
|
||||||
help_commands = ['-h', '--help', 'help']
|
help_commands = ["-h", "--help", "help"]
|
||||||
version_commands = ['-v', '--version', 'version']
|
version_commands = ["-v", "--version", "version"]
|
||||||
commands_exempt_from_license_check = help_commands + version_commands
|
commands_exempt_from_license_check = help_commands + version_commands
|
||||||
|
|
||||||
#---------------------------------------------------------------------#
|
#---------------------------------------------------------------------#
|
||||||
# EULA acceptance
|
# EULA acceptance
|
||||||
#---------------------------------------------------------------------#
|
#---------------------------------------------------------------------#
|
||||||
require 'license_acceptance/acceptor'
|
require "license_acceptance/acceptor"
|
||||||
begin
|
begin
|
||||||
if (commands_exempt_from_license_check & ARGV.map(&:downcase)).empty? && # Did they use a non-exempt command?
|
if (commands_exempt_from_license_check & ARGV.map(&:downcase)).empty? && # Did they use a non-exempt command?
|
||||||
!ARGV.empty? # Did they supply at least one command?
|
!ARGV.empty? # Did they supply at least one command?
|
||||||
LicenseAcceptance::Acceptor.check_and_persist(
|
LicenseAcceptance::Acceptor.check_and_persist(
|
||||||
'inspec',
|
"inspec",
|
||||||
Inspec::VERSION,
|
Inspec::VERSION,
|
||||||
logger: Inspec::Log,
|
logger: Inspec::Log
|
||||||
)
|
)
|
||||||
end
|
end
|
||||||
rescue LicenseAcceptance::LicenseNotAcceptedError
|
rescue LicenseAcceptance::LicenseNotAcceptedError
|
||||||
Inspec::Log.error 'InSpec cannot execute without accepting the license'
|
Inspec::Log.error "InSpec cannot execute without accepting the license"
|
||||||
Inspec::UI.new.exit(:license_not_accepted)
|
Inspec::UI.new.exit(:license_not_accepted)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -425,8 +425,8 @@ end
|
||||||
#---------------------------------------------------------------------#
|
#---------------------------------------------------------------------#
|
||||||
begin
|
begin
|
||||||
# Load v2 plugins. Manually check for plugin disablement.
|
# Load v2 plugins. Manually check for plugin disablement.
|
||||||
omit_core = ARGV.delete('--disable-core-plugins')
|
omit_core = ARGV.delete("--disable-core-plugins")
|
||||||
omit_user = ARGV.delete('--disable-user-plugins')
|
omit_user = ARGV.delete("--disable-user-plugins")
|
||||||
v2_loader = Inspec::Plugin::V2::Loader.new(omit_core_plugins: omit_core, omit_user_plugins: omit_user)
|
v2_loader = Inspec::Plugin::V2::Loader.new(omit_core_plugins: omit_core, omit_user_plugins: omit_user)
|
||||||
v2_loader.load_all
|
v2_loader.load_all
|
||||||
v2_loader.exit_on_load_error
|
v2_loader.exit_on_load_error
|
||||||
|
@ -437,23 +437,23 @@ begin
|
||||||
ctl.list.each { |x| ctl.load(x) }
|
ctl.list.each { |x| ctl.load(x) }
|
||||||
|
|
||||||
# load v1 CLI plugins before the InSpec CLI has been started
|
# load v1 CLI plugins before the InSpec CLI has been started
|
||||||
Inspec::Plugins::CLI.subcommands.each { |_subcommand, params|
|
Inspec::Plugins::CLI.subcommands.each do |_subcommand, params|
|
||||||
Inspec::InspecCLI.register(
|
Inspec::InspecCLI.register(
|
||||||
params[:klass],
|
params[:klass],
|
||||||
params[:subcommand_name],
|
params[:subcommand_name],
|
||||||
params[:usage],
|
params[:usage],
|
||||||
params[:description],
|
params[:description],
|
||||||
params[:options],
|
params[:options]
|
||||||
)
|
)
|
||||||
}
|
end
|
||||||
rescue Inspec::Plugin::V2::Exception => v2ex
|
rescue Inspec::Plugin::V2::Exception => v2ex
|
||||||
Inspec::Log.error v2ex.message
|
Inspec::Log.error v2ex.message
|
||||||
|
|
||||||
if ARGV.include?('--debug')
|
if ARGV.include?("--debug")
|
||||||
Inspec::Log.error v2ex.class.name
|
Inspec::Log.error v2ex.class.name
|
||||||
Inspec::Log.error v2ex.backtrace.join("\n")
|
Inspec::Log.error v2ex.backtrace.join("\n")
|
||||||
else
|
else
|
||||||
Inspec::Log.error 'Run again with --debug for a stacktrace.'
|
Inspec::Log.error "Run again with --debug for a stacktrace."
|
||||||
end
|
end
|
||||||
exit 2
|
exit 2
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
# Represents InSpec configuration. Merges defaults, config file options,
|
# Represents InSpec configuration. Merges defaults, config file options,
|
||||||
# and CLI arguments.
|
# and CLI arguments.
|
||||||
|
|
||||||
require 'pp'
|
require "pp"
|
||||||
require 'stringio'
|
require "stringio"
|
||||||
require 'forwardable'
|
require "forwardable"
|
||||||
require 'thor'
|
require "thor"
|
||||||
require 'base64'
|
require "base64"
|
||||||
require 'inspec/base_cli'
|
require "inspec/base_cli"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
class Config
|
class Config
|
||||||
|
@ -31,7 +31,7 @@ module Inspec
|
||||||
|
|
||||||
# This makes it easy to make a config with a mock backend.
|
# This makes it easy to make a config with a mock backend.
|
||||||
def self.mock(opts = {})
|
def self.mock(opts = {})
|
||||||
Inspec::Config.new({ backend: :mock }.merge(opts), StringIO.new('{}'))
|
Inspec::Config.new({ backend: :mock }.merge(opts), StringIO.new("{}"))
|
||||||
end
|
end
|
||||||
|
|
||||||
# Use this to get a cached version of the config. This prevents you from
|
# Use this to get a cached version of the config. This prevents you from
|
||||||
|
@ -62,11 +62,11 @@ module Inspec
|
||||||
return unless self[:diagnose]
|
return unless self[:diagnose]
|
||||||
puts "InSpec version: #{Inspec::VERSION}"
|
puts "InSpec version: #{Inspec::VERSION}"
|
||||||
puts "Train version: #{Train::VERSION}"
|
puts "Train version: #{Train::VERSION}"
|
||||||
puts 'Command line configuration:'
|
puts "Command line configuration:"
|
||||||
pp @cli_opts
|
pp @cli_opts
|
||||||
puts 'JSON configuration file:'
|
puts "JSON configuration file:"
|
||||||
pp @cfg_file_contents
|
pp @cfg_file_contents
|
||||||
puts 'Merged configuration:'
|
puts "Merged configuration:"
|
||||||
pp @merged_options
|
pp @merged_options
|
||||||
puts
|
puts
|
||||||
end
|
end
|
||||||
|
@ -74,7 +74,7 @@ module Inspec
|
||||||
# return all telemetry options from config
|
# return all telemetry options from config
|
||||||
# @return [Hash]
|
# @return [Hash]
|
||||||
def telemetry_options
|
def telemetry_options
|
||||||
final_options.select { |key, _| key.include?('telemetry') }
|
final_options.select { |key, _| key.include?("telemetry") }
|
||||||
end
|
end
|
||||||
|
|
||||||
#-----------------------------------------------------------------------#
|
#-----------------------------------------------------------------------#
|
||||||
|
@ -131,7 +131,7 @@ module Inspec
|
||||||
credentials.merge!(unprefixed_transport_options)
|
credentials.merge!(unprefixed_transport_options)
|
||||||
|
|
||||||
# If there are any prefixed options, merge them in, stripping the prefix.
|
# If there are any prefixed options, merge them in, stripping the prefix.
|
||||||
transport_prefix = transport_name.downcase.tr('-', '_') + '_'
|
transport_prefix = transport_name.downcase.tr("-", "_") + "_"
|
||||||
transport_options.each do |bare_option_name|
|
transport_options.each do |bare_option_name|
|
||||||
prefixed_option_name = transport_prefix + bare_option_name.to_s
|
prefixed_option_name = transport_prefix + bare_option_name.to_s
|
||||||
if final_options.key?(prefixed_option_name)
|
if final_options.key?(prefixed_option_name)
|
||||||
|
@ -150,7 +150,7 @@ module Inspec
|
||||||
|
|
||||||
# Default to local
|
# Default to local
|
||||||
unless @final_options.key?(:target)
|
unless @final_options.key?(:target)
|
||||||
credentials[:backend] = 'local'
|
credentials[:backend] = "local"
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -167,7 +167,7 @@ module Inspec
|
||||||
credset_name = _utc_find_credset_name(credentials, transport_name)
|
credset_name = _utc_find_credset_name(credentials, transport_name)
|
||||||
|
|
||||||
if credset_name
|
if credset_name
|
||||||
credset = @cfg_file_contents.dig('credentials', transport_name, credset_name)
|
credset = @cfg_file_contents.dig("credentials", transport_name, credset_name)
|
||||||
if credset
|
if credset
|
||||||
credentials.merge!(credset)
|
credentials.merge!(credset)
|
||||||
else
|
else
|
||||||
|
@ -195,7 +195,7 @@ module Inspec
|
||||||
|
|
||||||
# Regardless of our situation, end up with a readable IO object
|
# Regardless of our situation, end up with a readable IO object
|
||||||
def resolve_cfg_io(cli_opts, cfg_io)
|
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)
|
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)
|
cfg_io ||= check_for_piped_config(cli_opts)
|
||||||
return cfg_io if cfg_io
|
return cfg_io if cfg_io
|
||||||
|
|
||||||
|
@ -210,10 +210,10 @@ module Inspec
|
||||||
Inspec.deprecate(:cli_option_json_config) if cli_opts.key?(:json_config)
|
Inspec.deprecate(:cli_option_json_config) if cli_opts.key?(:json_config)
|
||||||
|
|
||||||
return nil unless cli_opt
|
return nil unless cli_opt
|
||||||
return nil unless cli_opt == '-'
|
return nil unless cli_opt == "-"
|
||||||
# This warning is here so that if a user invokes inspec with --config=-,
|
# This warning is here so that if a user invokes inspec with --config=-,
|
||||||
# they will have an explanation for why it appears to hang.
|
# they will have an explanation for why it appears to hang.
|
||||||
Inspec::Log.warn 'Reading JSON config from standard input' if STDIN.tty?
|
Inspec::Log.warn "Reading JSON config from standard input" if STDIN.tty?
|
||||||
STDIN
|
STDIN
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -222,7 +222,7 @@ module Inspec
|
||||||
Inspec.deprecate(:cli_option_json_config) if cli_opts.key?(:json_config)
|
Inspec.deprecate(:cli_option_json_config) if cli_opts.key?(:json_config)
|
||||||
|
|
||||||
if path.nil?
|
if path.nil?
|
||||||
default_path = File.join(Inspec.config_dir, 'config.json')
|
default_path = File.join(Inspec.config_dir, "config.json")
|
||||||
path = default_path if File.exist?(default_path)
|
path = default_path if File.exist?(default_path)
|
||||||
elsif !File.exist?(path)
|
elsif !File.exist?(path)
|
||||||
raise ArgumentError, "Could not read configuration file at #{path}"
|
raise ArgumentError, "Could not read configuration file at #{path}"
|
||||||
|
@ -249,7 +249,7 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def file_version
|
def file_version
|
||||||
@cfg_file_contents['version'] || :legacy
|
@cfg_file_contents["version"] || :legacy
|
||||||
end
|
end
|
||||||
|
|
||||||
def legacy_file?
|
def legacy_file?
|
||||||
|
@ -261,26 +261,26 @@ module Inspec
|
||||||
# Assume everything in the file is a CLI option
|
# Assume everything in the file is a CLI option
|
||||||
@cfg_file_contents
|
@cfg_file_contents
|
||||||
else
|
else
|
||||||
@cfg_file_contents['cli_options'] || {}
|
@cfg_file_contents["cli_options"] || {}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def config_file_reporter_options
|
def config_file_reporter_options
|
||||||
# This is assumed to be top-level in both legacy and 1.1.
|
# This is assumed to be top-level in both legacy and 1.1.
|
||||||
# Technically, you could sneak it in the 1.1 cli opts area.
|
# Technically, you could sneak it in the 1.1 cli opts area.
|
||||||
@cfg_file_contents.key?('reporter') ? { 'reporter' => @cfg_file_contents['reporter'] } : {}
|
@cfg_file_contents.key?("reporter") ? { "reporter" => @cfg_file_contents["reporter"] } : {}
|
||||||
end
|
end
|
||||||
|
|
||||||
#-----------------------------------------------------------------------#
|
#-----------------------------------------------------------------------#
|
||||||
# Validation
|
# Validation
|
||||||
#-----------------------------------------------------------------------#
|
#-----------------------------------------------------------------------#
|
||||||
def validate_config_file_contents!
|
def validate_config_file_contents!
|
||||||
version = @cfg_file_contents['version']
|
version = @cfg_file_contents["version"]
|
||||||
|
|
||||||
# Assume legacy format, which is unconstrained
|
# Assume legacy format, which is unconstrained
|
||||||
return unless version
|
return unless version
|
||||||
|
|
||||||
unless version == '1.1'
|
unless version == "1.1"
|
||||||
raise Inspec::ConfigError::Invalid, "Unsupported config file version '#{version}' - currently supported versions: 1.1"
|
raise Inspec::ConfigError::Invalid, "Unsupported config file version '#{version}' - currently supported versions: 1.1"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -296,23 +296,23 @@ module Inspec
|
||||||
return if reporters.nil?
|
return if reporters.nil?
|
||||||
# TODO: move this into a reporter plugin type system
|
# TODO: move this into a reporter plugin type system
|
||||||
valid_types = [
|
valid_types = [
|
||||||
'automate',
|
"automate",
|
||||||
'cli',
|
"cli",
|
||||||
'documentation',
|
"documentation",
|
||||||
'html',
|
"html",
|
||||||
'json',
|
"json",
|
||||||
'json-automate',
|
"json-automate",
|
||||||
'json-min',
|
"json-min",
|
||||||
'json-rspec',
|
"json-rspec",
|
||||||
'junit',
|
"junit",
|
||||||
'progress',
|
"progress",
|
||||||
'yaml',
|
"yaml",
|
||||||
]
|
]
|
||||||
|
|
||||||
reporters.each do |reporter_name, reporter_config|
|
reporters.each do |reporter_name, reporter_config|
|
||||||
raise NotImplementedError, "'#{reporter_name}' is not a valid reporter type." unless valid_types.include?(reporter_name)
|
raise NotImplementedError, "'#{reporter_name}' is not a valid reporter type." unless valid_types.include?(reporter_name)
|
||||||
|
|
||||||
next unless reporter_name == 'automate'
|
next unless reporter_name == "automate"
|
||||||
%w{token url}.each do |option|
|
%w{token url}.each do |option|
|
||||||
raise Inspec::ReporterError, "You must specify a automate #{option} via the config file." if reporter_config[option].nil?
|
raise Inspec::ReporterError, "You must specify a automate #{option} via the config file." if reporter_config[option].nil?
|
||||||
end
|
end
|
||||||
|
@ -321,10 +321,10 @@ module Inspec
|
||||||
# check to make sure we are only reporting one type to stdout
|
# check to make sure we are only reporting one type to stdout
|
||||||
stdout_reporters = 0
|
stdout_reporters = 0
|
||||||
reporters.each_value do |reporter_config|
|
reporters.each_value do |reporter_config|
|
||||||
stdout_reporters += 1 if reporter_config['stdout'] == true
|
stdout_reporters += 1 if reporter_config["stdout"] == true
|
||||||
end
|
end
|
||||||
|
|
||||||
raise ArgumentError, 'The option --reporter can only have a single report outputting to stdout.' if stdout_reporters > 1
|
raise ArgumentError, "The option --reporter can only have a single report outputting to stdout." if stdout_reporters > 1
|
||||||
end
|
end
|
||||||
|
|
||||||
#-----------------------------------------------------------------------#
|
#-----------------------------------------------------------------------#
|
||||||
|
@ -368,36 +368,36 @@ module Inspec
|
||||||
|
|
||||||
def finalize_parse_reporters(options) # rubocop:disable Metrics/AbcSize
|
def finalize_parse_reporters(options) # rubocop:disable Metrics/AbcSize
|
||||||
# default to cli report for ad-hoc runners
|
# default to cli report for ad-hoc runners
|
||||||
options['reporter'] = ['cli'] if options['reporter'].nil?
|
options["reporter"] = ["cli"] if options["reporter"].nil?
|
||||||
|
|
||||||
# parse out cli to proper report format
|
# parse out cli to proper report format
|
||||||
if options['reporter'].is_a?(Array)
|
if options["reporter"].is_a?(Array)
|
||||||
reports = {}
|
reports = {}
|
||||||
options['reporter'].each do |report|
|
options["reporter"].each do |report|
|
||||||
reporter_name, destination = report.split(':', 2)
|
reporter_name, destination = report.split(":", 2)
|
||||||
if destination.nil? || destination.strip == '-'
|
if destination.nil? || destination.strip == "-"
|
||||||
reports[reporter_name] = { 'stdout' => true }
|
reports[reporter_name] = { "stdout" => true }
|
||||||
else
|
else
|
||||||
reports[reporter_name] = {
|
reports[reporter_name] = {
|
||||||
'file' => destination,
|
"file" => destination,
|
||||||
'stdout' => false,
|
"stdout" => false,
|
||||||
}
|
}
|
||||||
reports[reporter_name]['target_id'] = options['target_id'] if options['target_id']
|
reports[reporter_name]["target_id"] = options["target_id"] if options["target_id"]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
options['reporter'] = reports
|
options["reporter"] = reports
|
||||||
end
|
end
|
||||||
|
|
||||||
# add in stdout if not specified
|
# add in stdout if not specified
|
||||||
if options['reporter'].is_a?(Hash)
|
if options["reporter"].is_a?(Hash)
|
||||||
options['reporter'].each do |reporter_name, config|
|
options["reporter"].each do |reporter_name, config|
|
||||||
options['reporter'][reporter_name] = {} if config.nil?
|
options["reporter"][reporter_name] = {} if config.nil?
|
||||||
options['reporter'][reporter_name]['stdout'] = true if options['reporter'][reporter_name].empty?
|
options["reporter"][reporter_name]["stdout"] = true if options["reporter"][reporter_name].empty?
|
||||||
options['reporter'][reporter_name]['target_id'] = options['target_id'] if options['target_id']
|
options["reporter"][reporter_name]["target_id"] = options["target_id"] if options["target_id"]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
validate_reporters!(options['reporter'])
|
validate_reporters!(options["reporter"])
|
||||||
options
|
options
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -408,38 +408,38 @@ module Inspec
|
||||||
# whenever it is used, it requires a value. Handle options that were
|
# whenever it is used, it requires a value. Handle options that were
|
||||||
# defined in such a way and require a value here:
|
# defined in such a way and require a value here:
|
||||||
%w{password sudo-password}.each do |option_name|
|
%w{password sudo-password}.each do |option_name|
|
||||||
snake_case_option_name = option_name.tr('-', '_').to_s
|
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
|
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."
|
raise ArgumentError, "Please provide a value for --#{option_name}. For example: --#{option_name}=hello."
|
||||||
end
|
end
|
||||||
|
|
||||||
# Infer `--sudo` if using `--sudo-password` without `--sudo`
|
# Infer `--sudo` if using `--sudo-password` without `--sudo`
|
||||||
if options['sudo_password'] && !options['sudo']
|
if options["sudo_password"] && !options["sudo"]
|
||||||
options['sudo'] = true
|
options["sudo"] = true
|
||||||
Inspec::Log.warn '`--sudo-password` used without `--sudo`. Adding `--sudo`.'
|
Inspec::Log.warn "`--sudo-password` used without `--sudo`. Adding `--sudo`."
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def finalize_compliance_login(options)
|
def finalize_compliance_login(options)
|
||||||
# check for compliance settings
|
# check for compliance settings
|
||||||
# This is always a hash, comes from config file, not CLI opts
|
# This is always a hash, comes from config file, not CLI opts
|
||||||
if options.key?('compliance')
|
if options.key?("compliance")
|
||||||
require 'plugins/inspec-compliance/lib/inspec-compliance/api'
|
require "plugins/inspec-compliance/lib/inspec-compliance/api"
|
||||||
InspecPlugins::Compliance::API.login(options['compliance'])
|
InspecPlugins::Compliance::API.login(options["compliance"])
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class Defaults
|
class Defaults
|
||||||
DEFAULTS = {
|
DEFAULTS = {
|
||||||
exec: {
|
exec: {
|
||||||
'reporter' => ['cli'],
|
"reporter" => ["cli"],
|
||||||
'show_progress' => false,
|
"show_progress" => false,
|
||||||
'color' => true,
|
"color" => true,
|
||||||
'create_lockfile' => true,
|
"create_lockfile" => true,
|
||||||
'backend_cache' => true,
|
"backend_cache" => true,
|
||||||
},
|
},
|
||||||
shell: {
|
shell: {
|
||||||
'reporter' => ['cli'],
|
"reporter" => ["cli"],
|
||||||
},
|
},
|
||||||
}.freeze
|
}.freeze
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
require 'inspec/dsl'
|
require "inspec/dsl"
|
||||||
require 'inspec/dsl_shared'
|
require "inspec/dsl_shared"
|
||||||
require 'rspec/core/dsl'
|
require "rspec/core/dsl"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
#
|
#
|
||||||
|
@ -233,7 +233,7 @@ module Inspec
|
||||||
|
|
||||||
def block_location(block, alternate_caller)
|
def block_location(block, alternate_caller)
|
||||||
if block.nil?
|
if block.nil?
|
||||||
alternate_caller[/^(.+:\d+):in .+$/, 1] || 'unknown'
|
alternate_caller[/^(.+:\d+):in .+$/, 1] || "unknown"
|
||||||
else
|
else
|
||||||
path, line = block.source_location
|
path, line = block.source_location
|
||||||
"#{File.basename(path)}:#{line}"
|
"#{File.basename(path)}:#{line}"
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'fileutils'
|
require "fileutils"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
#
|
#
|
||||||
|
@ -17,7 +17,7 @@ module Inspec
|
||||||
class Cache
|
class Cache
|
||||||
attr_reader :path
|
attr_reader :path
|
||||||
def initialize(path = nil)
|
def initialize(path = nil)
|
||||||
@path = path || File.join(Inspec.config_dir, 'cache')
|
@path = path || File.join(Inspec.config_dir, "cache")
|
||||||
FileUtils.mkdir_p(@path) unless File.directory?(@path)
|
FileUtils.mkdir_p(@path) unless File.directory?(@path)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
require 'inspec/dependencies/requirement'
|
require "inspec/dependencies/requirement"
|
||||||
require 'inspec/dependencies/resolver'
|
require "inspec/dependencies/resolver"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
#
|
#
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'yaml'
|
require "yaml"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
class Lockfile
|
class Lockfile
|
||||||
|
@ -8,15 +8,15 @@ module Inspec
|
||||||
|
|
||||||
def self.from_dependency_set(dep_set)
|
def self.from_dependency_set(dep_set)
|
||||||
lockfile_content = {
|
lockfile_content = {
|
||||||
'lockfile_version' => CURRENT_LOCKFILE_VERSION,
|
"lockfile_version" => CURRENT_LOCKFILE_VERSION,
|
||||||
'depends' => dep_set.to_array,
|
"depends" => dep_set.to_array,
|
||||||
}
|
}
|
||||||
new(lockfile_content)
|
new(lockfile_content)
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.from_content(content)
|
def self.from_content(content)
|
||||||
parsed_content = YAML.load(content)
|
parsed_content = YAML.load(content)
|
||||||
version = parsed_content['lockfile_version']
|
version = parsed_content["lockfile_version"]
|
||||||
raise "No lockfile_version set in #{path}!" if version.nil?
|
raise "No lockfile_version set in #{path}!" if version.nil?
|
||||||
validate_lockfile_version!(version.to_i)
|
validate_lockfile_version!(version.to_i)
|
||||||
new(parsed_content)
|
new(parsed_content)
|
||||||
|
@ -50,15 +50,15 @@ module Inspec
|
||||||
|
|
||||||
attr_reader :version, :deps
|
attr_reader :version, :deps
|
||||||
def initialize(lockfile_content_hash)
|
def initialize(lockfile_content_hash)
|
||||||
version = lockfile_content_hash['lockfile_version']
|
version = lockfile_content_hash["lockfile_version"]
|
||||||
@version = version.to_i
|
@version = version.to_i
|
||||||
parse_content_hash(lockfile_content_hash)
|
parse_content_hash(lockfile_content_hash)
|
||||||
end
|
end
|
||||||
|
|
||||||
def to_yaml
|
def to_yaml
|
||||||
{
|
{
|
||||||
'lockfile_version' => CURRENT_LOCKFILE_VERSION,
|
"lockfile_version" => CURRENT_LOCKFILE_VERSION,
|
||||||
'depends' => @deps.map { |i| stringify_keys(i) },
|
"depends" => @deps.map { |i| stringify_keys(i) },
|
||||||
}.to_yaml
|
}.to_yaml
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -84,7 +84,7 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def parse_content_hash_1(lockfile_content_hash)
|
def parse_content_hash_1(lockfile_content_hash)
|
||||||
@deps = lockfile_content_hash['depends']&.map { |i| symbolize_keys(i) }
|
@deps = lockfile_content_hash["depends"]&.map { |i| symbolize_keys(i) }
|
||||||
end
|
end
|
||||||
|
|
||||||
def mutate_hash_keys_with(hash, fun)
|
def mutate_hash_keys_with(hash, fun)
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
require 'inspec/cached_fetcher'
|
require "inspec/cached_fetcher"
|
||||||
require 'semverse'
|
require "semverse"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
#
|
#
|
||||||
|
@ -8,7 +8,7 @@ module Inspec
|
||||||
#
|
#
|
||||||
class Requirement
|
class Requirement
|
||||||
def self.from_metadata(dep, cache, opts)
|
def self.from_metadata(dep, cache, opts)
|
||||||
raise 'Cannot load empty dependency.' if dep.nil? || dep.empty?
|
raise "Cannot load empty dependency." if dep.nil? || dep.empty?
|
||||||
|
|
||||||
req_path = opts[:cwd]
|
req_path = opts[:cwd]
|
||||||
|
|
||||||
|
@ -81,13 +81,13 @@ module Inspec
|
||||||
|
|
||||||
def to_hash
|
def to_hash
|
||||||
h = {
|
h = {
|
||||||
'name' => name,
|
"name" => name,
|
||||||
'resolved_source' => resolved_source,
|
"resolved_source" => resolved_source,
|
||||||
'version_constraints' => version_constraints,
|
"version_constraints" => version_constraints,
|
||||||
}
|
}
|
||||||
|
|
||||||
if !dependencies.empty?
|
if !dependencies.empty?
|
||||||
h['dependencies'] = dependencies.map(&:to_hash)
|
h["dependencies"] = dependencies.map(&:to_hash)
|
||||||
end
|
end
|
||||||
|
|
||||||
h
|
h
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
require 'inspec/log'
|
require "inspec/log"
|
||||||
require 'inspec/errors'
|
require "inspec/errors"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
#
|
#
|
||||||
|
@ -35,7 +35,7 @@ module Inspec
|
||||||
deps.each do |dep|
|
deps.each do |dep|
|
||||||
if seen_items_local.include?(dep.name)
|
if seen_items_local.include?(dep.name)
|
||||||
problem_cookbook = if top_level
|
problem_cookbook = if top_level
|
||||||
'the inspec.yml for this profile.'
|
"the inspec.yml for this profile."
|
||||||
else
|
else
|
||||||
"the dependency information for #{path_string.split(' ').last}"
|
"the dependency information for #{path_string.split(' ').last}"
|
||||||
end
|
end
|
||||||
|
@ -47,7 +47,7 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
# Here deps is an Array of Inspec::Requirement
|
# Here deps is an Array of Inspec::Requirement
|
||||||
def resolve(deps, top_level = true, seen_items = {}, path_string = '') # rubocop:disable Metrics/AbcSize
|
def resolve(deps, top_level = true, seen_items = {}, path_string = "") # rubocop:disable Metrics/AbcSize
|
||||||
graph = {}
|
graph = {}
|
||||||
if top_level
|
if top_level
|
||||||
Inspec::Log.debug("Starting traversal of dependencies #{deps.map(&:to_s)}")
|
Inspec::Log.debug("Starting traversal of dependencies #{deps.map(&:to_s)}")
|
||||||
|
@ -79,7 +79,7 @@ module Inspec
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
Inspec::Log.debug('Dependency traversal complete.') if top_level
|
Inspec::Log.debug("Dependency traversal complete.") if top_level
|
||||||
graph
|
graph
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -13,11 +13,11 @@ module Inspec
|
||||||
def one(&block)
|
def one(&block)
|
||||||
return unless block_given?
|
return unless block_given?
|
||||||
instance_eval(&block)
|
instance_eval(&block)
|
||||||
@action.call('describe.one', @checks, nil)
|
@action.call("describe.one", @checks, nil)
|
||||||
end
|
end
|
||||||
|
|
||||||
def describe(*args, &block)
|
def describe(*args, &block)
|
||||||
@checks.push(['describe', args, block])
|
@checks.push(["describe", args, block])
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -3,18 +3,18 @@
|
||||||
module Inspec
|
module Inspec
|
||||||
module Dist
|
module Dist
|
||||||
# When referencing a product directly, like InSpec
|
# When referencing a product directly, like InSpec
|
||||||
PRODUCT_NAME = 'Chef InSpec'
|
PRODUCT_NAME = "Chef InSpec"
|
||||||
|
|
||||||
# The inspec executable
|
# The inspec executable
|
||||||
EXEC_NAME = 'inspec'
|
EXEC_NAME = "inspec"
|
||||||
|
|
||||||
# The name of the server product
|
# The name of the server product
|
||||||
SERVER_PRODUCT_NAME = 'Chef Server'
|
SERVER_PRODUCT_NAME = "Chef Server"
|
||||||
|
|
||||||
# name of the automate product
|
# name of the automate product
|
||||||
AUTOMATE_PRODUCT_NAME = 'Chef Automate'
|
AUTOMATE_PRODUCT_NAME = "Chef Automate"
|
||||||
|
|
||||||
# name of the compliance product
|
# name of the compliance product
|
||||||
COMPLIANCE_PRODUCT_NAME = 'Chef Compliance'
|
COMPLIANCE_PRODUCT_NAME = "Chef Compliance"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
# copyright: 2015, Dominik Richter
|
# copyright: 2015, Dominik Richter
|
||||||
require 'inspec/log'
|
require "inspec/log"
|
||||||
require 'inspec/plugin/v2'
|
require "inspec/plugin/v2"
|
||||||
|
|
||||||
module Inspec::DSL
|
module Inspec::DSL
|
||||||
def require_controls(id, &block)
|
def require_controls(id, &block)
|
||||||
|
@ -17,7 +17,7 @@ module Inspec::DSL
|
||||||
alias include_rules include_controls
|
alias include_rules include_controls
|
||||||
|
|
||||||
def require_resource(options = {})
|
def require_resource(options = {})
|
||||||
raise 'You must specify a specific resource name when calling require_resource()' if options[:resource].nil?
|
raise "You must specify a specific resource name when calling require_resource()" if options[:resource].nil?
|
||||||
|
|
||||||
from_profile = options[:profile] || profile_name
|
from_profile = options[:profile] || profile_name
|
||||||
target_name = options[:as] || options[:resource]
|
target_name = options[:as] || options[:resource]
|
||||||
|
@ -81,7 +81,7 @@ module Inspec::DSL
|
||||||
# remove all rules that were not registered
|
# remove all rules that were not registered
|
||||||
context.all_rules.each do |r|
|
context.all_rules.each do |r|
|
||||||
id = Inspec::Rule.rule_id(r)
|
id = Inspec::Rule.rule_id(r)
|
||||||
fid = Inspec::Rule.profile_id(r) + '/' + id
|
fid = Inspec::Rule.profile_id(r) + "/" + id
|
||||||
unless include_ctx.rules[id] || include_ctx.rules[fid]
|
unless include_ctx.rules[id] || include_ctx.rules[fid]
|
||||||
context.remove_rule(fid)
|
context.remove_rule(fid)
|
||||||
end
|
end
|
||||||
|
|
|
@ -9,7 +9,7 @@ module Inspec
|
||||||
alias __ruby_require require
|
alias __ruby_require require
|
||||||
|
|
||||||
def require(path)
|
def require(path)
|
||||||
rbpath = path + '.rb'
|
rbpath = path + ".rb"
|
||||||
return __ruby_require(path) if !@require_loader.exists?(rbpath)
|
return __ruby_require(path) if !@require_loader.exists?(rbpath)
|
||||||
return false if @require_loader.loaded?(rbpath)
|
return false if @require_loader.loaded?(rbpath)
|
||||||
|
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
require 'inspec/shell_detector'
|
require "inspec/shell_detector"
|
||||||
require 'erb'
|
require "erb"
|
||||||
require 'shellwords'
|
require "shellwords"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
class EnvPrinter
|
class EnvPrinter
|
||||||
attr_reader :shell
|
attr_reader :shell
|
||||||
|
|
||||||
EVAL_COMMANDS = {
|
EVAL_COMMANDS = {
|
||||||
'bash' => 'eval \"$(inspec env bash)\"',
|
"bash" => 'eval \"$(inspec env bash)\"',
|
||||||
'fish' => 'inspec env fish > ~/.config/fish/completions/inspec.fish',
|
"fish" => "inspec env fish > ~/.config/fish/completions/inspec.fish",
|
||||||
'zsh' => 'eval \"$(inspec env zsh)\"',
|
"zsh" => 'eval \"$(inspec env zsh)\"',
|
||||||
}.freeze
|
}.freeze
|
||||||
|
|
||||||
def initialize(command_class, shell = nil)
|
def initialize(command_class, shell = nil)
|
||||||
|
@ -35,7 +35,7 @@ module Inspec
|
||||||
private
|
private
|
||||||
|
|
||||||
def print_completion_for_shell
|
def print_completion_for_shell
|
||||||
erb = ERB.new(File.read(completion_template_path), nil, '-')
|
erb = ERB.new(File.read(completion_template_path), nil, "-")
|
||||||
puts erb.result(TemplateContext.new(@command_class).get_bindings)
|
puts erb.result(TemplateContext.new(@command_class).get_bindings)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -48,7 +48,7 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def completion_dir
|
def completion_dir
|
||||||
File.join(File.dirname(__FILE__), 'completions')
|
File.join(File.dirname(__FILE__), "completions")
|
||||||
end
|
end
|
||||||
|
|
||||||
def completion_template_path
|
def completion_template_path
|
||||||
|
@ -56,7 +56,7 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def shells_with_completions
|
def shells_with_completions
|
||||||
Dir.glob("#{completion_dir}/*.sh.erb").map { |f| File.basename(f, '.sh.erb') }
|
Dir.glob("#{completion_dir}/*.sh.erb").map { |f| File.basename(f, ".sh.erb") }
|
||||||
end
|
end
|
||||||
|
|
||||||
def print_usage_guidance
|
def print_usage_guidance
|
||||||
|
@ -90,7 +90,7 @@ module Inspec
|
||||||
|
|
||||||
def exit_no_shell
|
def exit_no_shell
|
||||||
if @detected
|
if @detected
|
||||||
$stderr.puts '# Unable to automatically detect shell and no shell was provided.'
|
$stderr.puts "# Unable to automatically detect shell and no shell was provided."
|
||||||
end
|
end
|
||||||
$stderr.puts <<~EOF
|
$stderr.puts <<~EOF
|
||||||
#
|
#
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
# copyright: 2016, Chef Software Inc.
|
# copyright: 2016, Chef Software Inc.
|
||||||
|
|
||||||
require 'rspec/expectations'
|
require "rspec/expectations"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
class Expect
|
class Expect
|
||||||
|
@ -22,11 +22,11 @@ module Inspec
|
||||||
def example_group
|
def example_group
|
||||||
that = self
|
that = self
|
||||||
|
|
||||||
opts = { 'caller' => calls[0][3] } # TODO: this needs overhaul. no magic #s
|
opts = { "caller" => calls[0][3] } # TODO: this needs overhaul. no magic #s
|
||||||
if !calls[0][3].nil? && !calls[0][3].empty? &&
|
if !calls[0][3].nil? && !calls[0][3].empty? &&
|
||||||
(m = calls[0][3][0].match(/^([^:]*):(\d+):/))
|
(m = calls[0][3][0].match(/^([^:]*):(\d+):/))
|
||||||
opts['file_path'] = m[0]
|
opts["file_path"] = m[0]
|
||||||
opts['line_number'] = m[1]
|
opts["line_number"] = m[1]
|
||||||
end
|
end
|
||||||
|
|
||||||
RSpec::Core::ExampleGroup.describe(that.value, opts) do
|
RSpec::Core::ExampleGroup.describe(that.value, opts) do
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'inspec/plugin/v1'
|
require "inspec/plugin/v1"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
class FetcherRegistry < PluginRegistry
|
class FetcherRegistry < PluginRegistry
|
||||||
|
@ -29,15 +29,15 @@ module Inspec
|
||||||
|
|
||||||
def self.fetcher(version)
|
def self.fetcher(version)
|
||||||
if version != 1
|
if version != 1
|
||||||
raise 'Only fetcher version 1 is supported!'
|
raise "Only fetcher version 1 is supported!"
|
||||||
end
|
end
|
||||||
Inspec::Plugins::Fetcher
|
Inspec::Plugins::Fetcher
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
require 'fetchers/local'
|
require "fetchers/local"
|
||||||
require 'fetchers/url'
|
require "fetchers/url"
|
||||||
require 'fetchers/git'
|
require "fetchers/git"
|
||||||
|
|
||||||
# TODO: Remove in 4.0 when Compliance fetcher plugin is created
|
# TODO: Remove in 4.0 when Compliance fetcher plugin is created
|
||||||
require 'plugins/inspec-compliance/lib/inspec-compliance/api'
|
require "plugins/inspec-compliance/lib/inspec-compliance/api"
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
require 'rubygems/package'
|
require "rubygems/package"
|
||||||
require 'zlib'
|
require "zlib"
|
||||||
require 'zip'
|
require "zip"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
class FileProvider
|
class FileProvider
|
||||||
|
@ -9,9 +9,9 @@ module Inspec
|
||||||
MockProvider.new(path)
|
MockProvider.new(path)
|
||||||
elsif File.directory?(path)
|
elsif File.directory?(path)
|
||||||
DirProvider.new(path)
|
DirProvider.new(path)
|
||||||
elsif File.exist?(path) && path.end_with?('.tar.gz', 'tgz')
|
elsif File.exist?(path) && path.end_with?(".tar.gz", "tgz")
|
||||||
TarProvider.new(path)
|
TarProvider.new(path)
|
||||||
elsif File.exist?(path) && path.end_with?('.zip')
|
elsif File.exist?(path) && path.end_with?(".zip")
|
||||||
ZipProvider.new(path)
|
ZipProvider.new(path)
|
||||||
elsif File.exist?(path)
|
elsif File.exist?(path)
|
||||||
DirProvider.new(path)
|
DirProvider.new(path)
|
||||||
|
@ -71,7 +71,7 @@ module Inspec
|
||||||
@files = if File.file?(path)
|
@files = if File.file?(path)
|
||||||
[path]
|
[path]
|
||||||
else
|
else
|
||||||
Dir[File.join(Shellwords.shellescape(path), '**', '*')]
|
Dir[File.join(Shellwords.shellescape(path), "**", "*")]
|
||||||
end
|
end
|
||||||
@path = path
|
@path = path
|
||||||
end
|
end
|
||||||
|
@ -98,13 +98,13 @@ module Inspec
|
||||||
@files = []
|
@files = []
|
||||||
walk_zip(@path) do |io|
|
walk_zip(@path) do |io|
|
||||||
while (entry = io.get_next_entry)
|
while (entry = io.get_next_entry)
|
||||||
name = entry.name.sub(%r{/+$}, '')
|
name = entry.name.sub(%r{/+$}, "")
|
||||||
@files.push(name) unless name.empty? || name.squeeze('/') =~ %r{\.{2}(?:/|\z)}
|
@files.push(name) unless name.empty? || name.squeeze("/") =~ %r{\.{2}(?:/|\z)}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def extract(destination_path = '.')
|
def extract(destination_path = ".")
|
||||||
FileUtils.mkdir_p(destination_path)
|
FileUtils.mkdir_p(destination_path)
|
||||||
|
|
||||||
Zip::File.open(@path) do |archive|
|
Zip::File.open(@path) do |archive|
|
||||||
|
@ -155,17 +155,17 @@ module Inspec
|
||||||
@files = tar.find_all(&:file?)
|
@files = tar.find_all(&:file?)
|
||||||
|
|
||||||
# delete all entries with no name
|
# delete all entries with no name
|
||||||
@files = @files.find_all { |x| !x.full_name.empty? && x.full_name.squeeze('/') !~ %r{\.{2}(?:/|\z)} }
|
@files = @files.find_all { |x| !x.full_name.empty? && x.full_name.squeeze("/") !~ %r{\.{2}(?:/|\z)} }
|
||||||
|
|
||||||
# delete all entries that have a PaxHeader
|
# delete all entries that have a PaxHeader
|
||||||
@files = @files.delete_if { |x| x.full_name.include?('PaxHeader/') }
|
@files = @files.delete_if { |x| x.full_name.include?("PaxHeader/") }
|
||||||
|
|
||||||
# replace all items of the array simply with the relative filename of the file
|
# replace all items of the array simply with the relative filename of the file
|
||||||
@files.map! { |x| Pathname.new(x.full_name).relative_path_from(Pathname.new('.')).to_s }
|
@files.map! { |x| Pathname.new(x.full_name).relative_path_from(Pathname.new(".")).to_s }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def extract(destination_path = '.')
|
def extract(destination_path = ".")
|
||||||
FileUtils.mkdir_p(destination_path)
|
FileUtils.mkdir_p(destination_path)
|
||||||
|
|
||||||
walk_tar(@path) do |files|
|
walk_tar(@path) do |files|
|
||||||
|
@ -178,7 +178,7 @@ module Inspec
|
||||||
FileUtils.remove_entry(final_path) if File.exist?(final_path)
|
FileUtils.remove_entry(final_path) if File.exist?(final_path)
|
||||||
|
|
||||||
FileUtils.mkdir_p(File.dirname(final_path))
|
FileUtils.mkdir_p(File.dirname(final_path))
|
||||||
File.open(final_path, 'wb') { |f| f.write(file.read) }
|
File.open(final_path, "wb") { |f| f.write(file.read) }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -213,8 +213,8 @@ module Inspec
|
||||||
|
|
||||||
class RelativeFileProvider
|
class RelativeFileProvider
|
||||||
BLACKLIST_FILES = [
|
BLACKLIST_FILES = [
|
||||||
'/pax_global_header',
|
"/pax_global_header",
|
||||||
'pax_global_header',
|
"pax_global_header",
|
||||||
].freeze
|
].freeze
|
||||||
|
|
||||||
attr_reader :files
|
attr_reader :files
|
||||||
|
@ -238,7 +238,7 @@ module Inspec
|
||||||
.map { |x| x[prefix.length..-1] }
|
.map { |x| x[prefix.length..-1] }
|
||||||
.map do |x|
|
.map do |x|
|
||||||
path = Pathname.new(x)
|
path = Pathname.new(x)
|
||||||
path.absolute? ? path.to_s : path.relative_path_from(Pathname.new('.')).to_s
|
path.absolute? ? path.to_s : path.relative_path_from(Pathname.new(".")).to_s
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -258,7 +258,7 @@ module Inspec
|
||||||
private
|
private
|
||||||
|
|
||||||
def get_prefix(fs)
|
def get_prefix(fs)
|
||||||
return '' if fs.empty?
|
return "" if fs.empty?
|
||||||
|
|
||||||
# filter backlisted files
|
# filter backlisted files
|
||||||
fs -= BLACKLIST_FILES
|
fs -= BLACKLIST_FILES
|
||||||
|
@ -287,15 +287,15 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def get_files_prefix(fs)
|
def get_files_prefix(fs)
|
||||||
return '' if fs.empty?
|
return "" if fs.empty?
|
||||||
|
|
||||||
file = fs[0]
|
file = fs[0]
|
||||||
bn = File.basename(file)
|
bn = File.basename(file)
|
||||||
# no more prefixes
|
# no more prefixes
|
||||||
return '' if bn == file
|
return "" if bn == file
|
||||||
|
|
||||||
i = file.rindex(bn)
|
i = file.rindex(bn)
|
||||||
pre = file[0..i-1]
|
pre = file[0..i - 1]
|
||||||
|
|
||||||
rest = fs.find_all { |f| !f.start_with?(pre) }
|
rest = fs.find_all { |f| !f.start_with?(pre) }
|
||||||
return pre if rest.empty?
|
return pre if rest.empty?
|
||||||
|
@ -303,8 +303,8 @@ module Inspec
|
||||||
new_pre = get_prefix(rest)
|
new_pre = get_prefix(rest)
|
||||||
return new_pre if pre.start_with? new_pre
|
return new_pre if pre.start_with? new_pre
|
||||||
# edge case: completely different prefixes; retry prefix detection
|
# edge case: completely different prefixes; retry prefix detection
|
||||||
a = File.dirname(pre + 'a')
|
a = File.dirname(pre + "a")
|
||||||
b = File.dirname(new_pre + 'b')
|
b = File.dirname(new_pre + "b")
|
||||||
get_prefix([a, b])
|
get_prefix([a, b])
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,3 +1,3 @@
|
||||||
require 'inspec/formatters/base'
|
require "inspec/formatters/base"
|
||||||
require 'inspec/formatters/json_rspec'
|
require "inspec/formatters/json_rspec"
|
||||||
require 'inspec/formatters/show_progress'
|
require "inspec/formatters/show_progress"
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
require 'rspec/core'
|
require "rspec/core"
|
||||||
require 'rspec/core/formatters/base_formatter'
|
require "rspec/core/formatters/base_formatter"
|
||||||
|
|
||||||
module Inspec::Formatters
|
module Inspec::Formatters
|
||||||
class Base < RSpec::Core::Formatters::BaseFormatter
|
class Base < RSpec::Core::Formatters::BaseFormatter
|
||||||
|
@ -43,7 +43,7 @@ module Inspec::Formatters
|
||||||
next unless e
|
next unless e
|
||||||
|
|
||||||
if example.metadata[:sensitive]
|
if example.metadata[:sensitive]
|
||||||
hash[:message] = '*** sensitive output suppressed ***'
|
hash[:message] = "*** sensitive output suppressed ***"
|
||||||
else
|
else
|
||||||
hash[:message] = exception_message(e)
|
hash[:message] = exception_message(e)
|
||||||
end
|
end
|
||||||
|
@ -101,9 +101,9 @@ module Inspec::Formatters
|
||||||
|
|
||||||
all_unique_controls.each do |control|
|
all_unique_controls.each do |control|
|
||||||
next unless control[:results]
|
next unless control[:results]
|
||||||
if control[:results].any? { |r| r[:status] == 'failed' }
|
if control[:results].any? { |r| r[:status] == "failed" }
|
||||||
failed += 1
|
failed += 1
|
||||||
elsif control[:results].any? { |r| r[:status] == 'skipped' }
|
elsif control[:results].any? { |r| r[:status] == "skipped" }
|
||||||
skipped += 1
|
skipped += 1
|
||||||
else
|
else
|
||||||
passed += 1
|
passed += 1
|
||||||
|
@ -162,8 +162,8 @@ module Inspec::Formatters
|
||||||
res[:profile_id] = pid
|
res[:profile_id] = pid
|
||||||
end
|
end
|
||||||
|
|
||||||
if res[:status] == 'pending'
|
if res[:status] == "pending"
|
||||||
res[:status] = 'skipped'
|
res[:status] = "skipped"
|
||||||
res[:skip_message] = example.metadata[:description]
|
res[:skip_message] = example.metadata[:description]
|
||||||
res[:resource] = example.metadata[:described_class].to_s
|
res[:resource] = example.metadata[:described_class].to_s
|
||||||
end
|
end
|
||||||
|
@ -173,7 +173,7 @@ module Inspec::Formatters
|
||||||
|
|
||||||
def format_expectation_message(example)
|
def format_expectation_message(example)
|
||||||
if (example.metadata[:example_group][:description_args].first == example.metadata[:example_group][:described_class]) ||
|
if (example.metadata[:example_group][:description_args].first == example.metadata[:example_group][:described_class]) ||
|
||||||
example.metadata[:example_group][:described_class].nil?
|
example.metadata[:example_group][:described_class].nil?
|
||||||
example.metadata[:description]
|
example.metadata[:description]
|
||||||
else
|
else
|
||||||
"#{example.metadata[:example_group][:description]} #{example.metadata[:description]}"
|
"#{example.metadata[:example_group][:description]} #{example.metadata[:description]}"
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
module Inspec
|
module Inspec
|
||||||
def self.config_dir
|
def self.config_dir
|
||||||
ENV['INSPEC_CONFIG_DIR'] ? ENV['INSPEC_CONFIG_DIR'] : File.join(Dir.home, '.inspec')
|
ENV["INSPEC_CONFIG_DIR"] ? ENV["INSPEC_CONFIG_DIR"] : File.join(Dir.home, ".inspec")
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.src_root
|
def self.src_root
|
||||||
File.expand_path(File.join(__FILE__, '..', '..', '..'))
|
File.expand_path(File.join(__FILE__, "..", "..", ".."))
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
# Impact scores based off CVSS 3.0
|
# Impact scores based off CVSS 3.0
|
||||||
module Inspec::Impact
|
module Inspec::Impact
|
||||||
IMPACT_SCORES = {
|
IMPACT_SCORES = {
|
||||||
'none' => 0.0,
|
"none" => 0.0,
|
||||||
'low' => 0.1,
|
"low" => 0.1,
|
||||||
'medium' => 0.4,
|
"medium" => 0.4,
|
||||||
'high' => 0.7,
|
"high" => 0.7,
|
||||||
'critical' => 0.9,
|
"critical" => 0.9,
|
||||||
}.freeze
|
}.freeze
|
||||||
|
|
||||||
def self.impact_from_string(value)
|
def self.impact_from_string(value)
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
require 'forwardable'
|
require "forwardable"
|
||||||
require 'singleton'
|
require "singleton"
|
||||||
require 'inspec/objects/input'
|
require "inspec/objects/input"
|
||||||
require 'inspec/secrets'
|
require "inspec/secrets"
|
||||||
require 'inspec/exceptions'
|
require "inspec/exceptions"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
# The InputRegistry's responsibilities include:
|
# The InputRegistry's responsibilities include:
|
||||||
|
@ -29,10 +29,10 @@ module Inspec
|
||||||
# Upon creation, activate all input plugins
|
# Upon creation, activate all input plugins
|
||||||
activators = Inspec::Plugin::V2::Registry.instance.find_activators(plugin_type: :input)
|
activators = Inspec::Plugin::V2::Registry.instance.find_activators(plugin_type: :input)
|
||||||
|
|
||||||
@plugins = activators.map { |activator|
|
@plugins = activators.map do |activator|
|
||||||
activator.activate!
|
activator.activate!
|
||||||
activator.implementation_class.new
|
activator.implementation_class.new
|
||||||
}
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
#-------------------------------------------------------------#
|
#-------------------------------------------------------------#
|
||||||
|
@ -88,7 +88,7 @@ module Inspec
|
||||||
action: :fetch,
|
action: :fetch,
|
||||||
provider: plugin.class.plugin_name,
|
provider: plugin.class.plugin_name,
|
||||||
priority: plugin.default_priority,
|
priority: plugin.default_priority,
|
||||||
hit: !response.nil?,
|
hit: !response.nil?
|
||||||
)
|
)
|
||||||
evt.value = response unless response.nil?
|
evt.value = response unless response.nil?
|
||||||
inputs_by_profile[profile_name][input_name].events << evt
|
inputs_by_profile[profile_name][input_name].events << evt
|
||||||
|
@ -149,7 +149,7 @@ module Inspec
|
||||||
provider: :runner_api, # TODO: suss out if audit cookbook or kitchen-inspec or something unknown
|
provider: :runner_api, # TODO: suss out if audit cookbook or kitchen-inspec or something unknown
|
||||||
priority: 40,
|
priority: 40,
|
||||||
file: loc.path,
|
file: loc.path,
|
||||||
line: loc.lineno,
|
line: loc.lineno
|
||||||
)
|
)
|
||||||
find_or_register_input(input_name, profile_name, event: evt)
|
find_or_register_input(input_name, profile_name, event: evt)
|
||||||
end
|
end
|
||||||
|
@ -169,7 +169,7 @@ module Inspec
|
||||||
if data.nil?
|
if data.nil?
|
||||||
raise Inspec::Exceptions::SecretsBackendNotFound,
|
raise Inspec::Exceptions::SecretsBackendNotFound,
|
||||||
"Cannot find parser for inputs file '#{path}'. " \
|
"Cannot find parser for inputs file '#{path}'. " \
|
||||||
'Check to make sure file has the appropriate extension.'
|
"Check to make sure file has the appropriate extension."
|
||||||
end
|
end
|
||||||
|
|
||||||
next if data.inputs.nil?
|
next if data.inputs.nil?
|
||||||
|
@ -178,7 +178,7 @@ module Inspec
|
||||||
value: input_value,
|
value: input_value,
|
||||||
provider: :cli_files,
|
provider: :cli_files,
|
||||||
priority: 40,
|
priority: 40,
|
||||||
file: path,
|
file: path
|
||||||
# TODO: any way we could get a line number?
|
# TODO: any way we could get a line number?
|
||||||
)
|
)
|
||||||
find_or_register_input(input_name, profile_name, event: evt)
|
find_or_register_input(input_name, profile_name, event: evt)
|
||||||
|
@ -190,13 +190,13 @@ module Inspec
|
||||||
unless File.exist?(path)
|
unless File.exist?(path)
|
||||||
raise Inspec::Exceptions::InputsFileDoesNotExist,
|
raise Inspec::Exceptions::InputsFileDoesNotExist,
|
||||||
"Cannot find input file '#{path}'. " \
|
"Cannot find input file '#{path}'. " \
|
||||||
'Check to make sure file exists.'
|
"Check to make sure file exists."
|
||||||
end
|
end
|
||||||
|
|
||||||
unless File.readable?(path)
|
unless File.readable?(path)
|
||||||
raise Inspec::Exceptions::InputsFileNotReadable,
|
raise Inspec::Exceptions::InputsFileNotReadable,
|
||||||
"Cannot read input file '#{path}'. " \
|
"Cannot read input file '#{path}'. " \
|
||||||
'Check to make sure file is readable.'
|
"Check to make sure file is readable."
|
||||||
end
|
end
|
||||||
|
|
||||||
true
|
true
|
||||||
|
@ -211,7 +211,7 @@ module Inspec
|
||||||
profile_metadata_obj.params[:attributes].each do |input_orig|
|
profile_metadata_obj.params[:attributes].each do |input_orig|
|
||||||
input_options = input_orig.dup
|
input_options = input_orig.dup
|
||||||
input_name = input_options.delete(:name)
|
input_name = input_options.delete(:name)
|
||||||
input_options.merge!({ priority: 30, provider: :profile_metadata, file: File.join(profile_name, 'inspec.yml') })
|
input_options.merge!({ priority: 30, provider: :profile_metadata, file: File.join(profile_name, "inspec.yml") })
|
||||||
evt = Inspec::Input.infer_event(input_options)
|
evt = Inspec::Input.infer_event(input_options)
|
||||||
|
|
||||||
# Profile metadata may set inputs in other profiles by naming them.
|
# Profile metadata may set inputs in other profiles by naming them.
|
||||||
|
@ -227,7 +227,7 @@ module Inspec
|
||||||
event: evt)
|
event: evt)
|
||||||
end
|
end
|
||||||
elsif profile_metadata_obj.params.key?(:attributes)
|
elsif profile_metadata_obj.params.key?(:attributes)
|
||||||
Inspec::Log.warn 'Inputs must be defined as an Array. Skipping current definition.'
|
Inspec::Log.warn "Inputs must be defined as an Array. Skipping current definition."
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
require 'inspec/plugin/v1/plugin_types/resource'
|
require "inspec/plugin/v1/plugin_types/resource"
|
||||||
require 'inspec/dsl_shared'
|
require "inspec/dsl_shared"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
#
|
#
|
||||||
|
@ -48,7 +48,7 @@ module Inspec
|
||||||
# Provide the local binding for this context which is necessary for
|
# Provide the local binding for this context which is necessary for
|
||||||
# calls to `require` to create all dependent objects in the correct
|
# calls to `require` to create all dependent objects in the correct
|
||||||
# context.
|
# context.
|
||||||
res.instance_variable_set('@inspec_binding', res.instance_eval('binding'))
|
res.instance_variable_set("@inspec_binding", res.instance_eval("binding"))
|
||||||
res
|
res
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'mixlib/log'
|
require "mixlib/log"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
class Log
|
class Log
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
# Copyright 2015 Dominik Richter
|
# Copyright 2015 Dominik Richter
|
||||||
|
|
||||||
require 'logger'
|
require "logger"
|
||||||
require 'rubygems/version'
|
require "rubygems/version"
|
||||||
require 'rubygems/requirement'
|
require "rubygems/requirement"
|
||||||
require 'semverse'
|
require "semverse"
|
||||||
require 'erb'
|
require "erb"
|
||||||
|
|
||||||
require 'inspec/version'
|
require "inspec/version"
|
||||||
require 'inspec/utils/spdx'
|
require "inspec/utils/spdx"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
# Extract metadata.rb information
|
# Extract metadata.rb information
|
||||||
|
@ -20,7 +20,7 @@ module Inspec
|
||||||
def initialize(ref, logger = nil)
|
def initialize(ref, logger = nil)
|
||||||
@ref = ref
|
@ref = ref
|
||||||
@logger = logger || Logger.new(nil)
|
@logger = logger || Logger.new(nil)
|
||||||
@content = ''
|
@content = ""
|
||||||
@params = {}
|
@params = {}
|
||||||
@missing_methods = []
|
@missing_methods = []
|
||||||
end
|
end
|
||||||
|
@ -80,12 +80,12 @@ module Inspec
|
||||||
|
|
||||||
if %r{[\/\\]} =~ params[:name]
|
if %r{[\/\\]} =~ params[:name]
|
||||||
errors.push("The profile name (#{params[:name]}) contains a slash" \
|
errors.push("The profile name (#{params[:name]}) contains a slash" \
|
||||||
' which is not permitted. Please remove all slashes from `inspec.yml`.')
|
" which is not permitted. Please remove all slashes from `inspec.yml`.")
|
||||||
end
|
end
|
||||||
|
|
||||||
# if version is set, ensure it is correct
|
# if version is set, ensure it is correct
|
||||||
if !params[:version].nil? && !valid_version?(params[:version])
|
if !params[:version].nil? && !valid_version?(params[:version])
|
||||||
errors.push('Version needs to be in SemVer format')
|
errors.push("Version needs to be in SemVer format")
|
||||||
end
|
end
|
||||||
|
|
||||||
%w{title summary maintainer copyright license}.each do |field|
|
%w{title summary maintainer copyright license}.each do |field|
|
||||||
|
@ -145,8 +145,8 @@ module Inspec
|
||||||
x
|
x
|
||||||
when Array
|
when Array
|
||||||
logger.warn(
|
logger.warn(
|
||||||
'Failed to read supports entry that is an array. Please use '\
|
"Failed to read supports entry that is an array. Please use "\
|
||||||
'the `supports: {os-family: xyz}` syntax.',
|
"the `supports: {os-family: xyz}` syntax."
|
||||||
)
|
)
|
||||||
nil
|
nil
|
||||||
when nil then nil
|
when nil then nil
|
||||||
|
@ -184,14 +184,14 @@ module Inspec
|
||||||
# unit tests that look for warning sequences
|
# unit tests that look for warning sequences
|
||||||
return if original_target.to_s.empty?
|
return if original_target.to_s.empty?
|
||||||
metadata.params[:title] = "tests from #{original_target}"
|
metadata.params[:title] = "tests from #{original_target}"
|
||||||
metadata.params[:name] = metadata.params[:title].gsub(%r{[\/\\]}, '.')
|
metadata.params[:name] = metadata.params[:title].gsub(%r{[\/\\]}, ".")
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.finalize(metadata, profile_id, options, logger = nil)
|
def self.finalize(metadata, profile_id, options, logger = nil)
|
||||||
return nil if metadata.nil?
|
return nil if metadata.nil?
|
||||||
param = metadata.params || {}
|
param = metadata.params || {}
|
||||||
options ||= {}
|
options ||= {}
|
||||||
param['version'] = param['version'].to_s unless param['version'].nil?
|
param["version"] = param["version"].to_s unless param["version"].nil?
|
||||||
metadata.params = symbolize_keys(param)
|
metadata.params = symbolize_keys(param)
|
||||||
metadata.params[:supports] = finalize_supports(metadata.params[:supports], logger)
|
metadata.params[:supports] = finalize_supports(metadata.params[:supports], logger)
|
||||||
finalize_name(metadata, profile_id, options[:target])
|
finalize_name(metadata, profile_id, options[:target])
|
||||||
|
@ -217,9 +217,9 @@ module Inspec
|
||||||
# NOTE there doesn't have to exist an actual file, it may come from an
|
# NOTE there doesn't have to exist an actual file, it may come from an
|
||||||
# archive (i.e., content)
|
# archive (i.e., content)
|
||||||
case File.basename(ref)
|
case File.basename(ref)
|
||||||
when 'inspec.yml'
|
when "inspec.yml"
|
||||||
from_yaml(ref, content, profile_id, logger)
|
from_yaml(ref, content, profile_id, logger)
|
||||||
when 'metadata.rb'
|
when "metadata.rb"
|
||||||
from_ruby(ref, content, profile_id, logger)
|
from_ruby(ref, content, profile_id, logger)
|
||||||
else
|
else
|
||||||
logger ||= Logger.new(nil)
|
logger ||= Logger.new(nil)
|
||||||
|
|
|
@ -2,16 +2,16 @@ module Inspec
|
||||||
module MethodSource
|
module MethodSource
|
||||||
def self.code_at(location, source_reader)
|
def self.code_at(location, source_reader)
|
||||||
# TODO: logger for these cases
|
# TODO: logger for these cases
|
||||||
return '' if location.nil? || location[:ref].nil? || location[:line].nil?
|
return "" if location.nil? || location[:ref].nil? || location[:line].nil?
|
||||||
return '' unless source_reader && source_reader.target
|
return "" unless source_reader && source_reader.target
|
||||||
|
|
||||||
# TODO: Non-controls still need more detection
|
# TODO: Non-controls still need more detection
|
||||||
ref = location[:ref]
|
ref = location[:ref]
|
||||||
ref = ref.sub(source_reader.target.prefix, '')
|
ref = ref.sub(source_reader.target.prefix, "")
|
||||||
src = source_reader.tests[ref]
|
src = source_reader.tests[ref]
|
||||||
return '' if src.nil?
|
return "" if src.nil?
|
||||||
|
|
||||||
::MethodSource.expression_at(src.lines, location[:line]).force_encoding('utf-8')
|
::MethodSource.expression_at(src.lines, location[:line]).force_encoding("utf-8")
|
||||||
rescue SyntaxError => e
|
rescue SyntaxError => e
|
||||||
raise ::MethodSource::SourceNotFoundError,
|
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}"
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
module Inspec
|
module Inspec
|
||||||
autoload :Input, 'inspec/objects/input'
|
autoload :Input, "inspec/objects/input"
|
||||||
autoload :Tag, 'inspec/objects/tag'
|
autoload :Tag, "inspec/objects/tag"
|
||||||
autoload :Control, 'inspec/objects/control'
|
autoload :Control, "inspec/objects/control"
|
||||||
autoload :Describe, 'inspec/objects/describe'
|
autoload :Describe, "inspec/objects/describe"
|
||||||
autoload :EachLoop, 'inspec/objects/each_loop'
|
autoload :EachLoop, "inspec/objects/each_loop"
|
||||||
autoload :List, 'inspec/objects/list'
|
autoload :List, "inspec/objects/list"
|
||||||
autoload :OrTest, 'inspec/objects/or_test'
|
autoload :OrTest, "inspec/objects/or_test"
|
||||||
autoload :RubyHelper, 'inspec/objects/ruby_helper'
|
autoload :RubyHelper, "inspec/objects/ruby_helper"
|
||||||
autoload :Test, 'inspec/objects/test'
|
autoload :Test, "inspec/objects/test"
|
||||||
autoload :Value, 'inspec/objects/value'
|
autoload :Value, "inspec/objects/value"
|
||||||
end
|
end
|
||||||
|
|
|
@ -32,7 +32,7 @@ module Inspec
|
||||||
res.push " title #{title.inspect}" unless title.to_s.empty?
|
res.push " title #{title.inspect}" unless title.to_s.empty?
|
||||||
descriptions.each do |label, text|
|
descriptions.each do |label, text|
|
||||||
if label == :default
|
if label == :default
|
||||||
next if text.nil? or text == '' # don't render empty/nil desc
|
next if text.nil? || (text == "") # don't render empty/nil desc
|
||||||
res.push " desc #{prettyprint_text(text, 2)}"
|
res.push " desc #{prettyprint_text(text, 2)}"
|
||||||
else
|
else
|
||||||
res.push " desc #{label.to_s.inspect}, #{prettyprint_text(text, 2)}"
|
res.push " desc #{label.to_s.inspect}, #{prettyprint_text(text, 2)}"
|
||||||
|
@ -43,7 +43,7 @@ module Inspec
|
||||||
refs.each { |t| res.push(" ref #{print_ref(t)}") }
|
refs.each { |t| res.push(" ref #{print_ref(t)}") }
|
||||||
res.push " only_if { #{only_if} }" if only_if
|
res.push " only_if { #{only_if} }" if only_if
|
||||||
tests.each { |t| res.push(indent(t.to_ruby, 2)) }
|
tests.each { |t| res.push(indent(t.to_ruby, 2)) }
|
||||||
res.push 'end'
|
res.push "end"
|
||||||
res.join("\n")
|
res.join("\n")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -52,7 +52,7 @@ module Inspec
|
||||||
def print_ref(x)
|
def print_ref(x)
|
||||||
return x.inspect if x.is_a?(String)
|
return x.inspect if x.is_a?(String)
|
||||||
raise "Cannot process the ref: #{x}" unless x.is_a?(Hash)
|
raise "Cannot process the ref: #{x}" unless x.is_a?(Hash)
|
||||||
'('+x.inspect+')'
|
"(" + x.inspect + ")"
|
||||||
end
|
end
|
||||||
|
|
||||||
# Pretty-print a text block of InSpec code
|
# Pretty-print a text block of InSpec code
|
||||||
|
@ -63,13 +63,13 @@ module Inspec
|
||||||
def prettyprint_text(s, depth)
|
def prettyprint_text(s, depth)
|
||||||
txt = s.to_s.inspect.gsub('\n', "\n")
|
txt = s.to_s.inspect.gsub('\n', "\n")
|
||||||
return txt if !txt.include?("\n")
|
return txt if !txt.include?("\n")
|
||||||
middle = indent(txt[1..-2], depth+2)
|
middle = indent(txt[1..-2], depth + 2)
|
||||||
txt[0] + "\n" + middle + "\n" + ' '*depth + txt[-1]
|
txt[0] + "\n" + middle + "\n" + " " * depth + txt[-1]
|
||||||
end
|
end
|
||||||
|
|
||||||
def indent(txt, d)
|
def indent(txt, d)
|
||||||
dt = ' '*d
|
dt = " " * d
|
||||||
dt + txt.gsub("\n", "\n"+dt)
|
dt + txt.gsub("\n", "\n" + dt)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -9,24 +9,24 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def to_ruby
|
def to_ruby
|
||||||
itsy = 'it'
|
itsy = "it"
|
||||||
unless its.nil?
|
unless its.nil?
|
||||||
if its.is_a? Array
|
if its.is_a? Array
|
||||||
itsy = 'its(' + its.inspect + ')'
|
itsy = "its(" + its.inspect + ")"
|
||||||
else
|
else
|
||||||
itsy = 'its(' + its.to_s.inspect + ')'
|
itsy = "its(" + its.to_s.inspect + ")"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
naughty = negated ? '_not' : ''
|
naughty = negated ? "_not" : ""
|
||||||
xpect = if expectation.nil?
|
xpect = if expectation.nil?
|
||||||
''
|
""
|
||||||
elsif expectation.class == Regexp
|
elsif expectation.class == Regexp
|
||||||
# without this, xpect values like / \/zones\// will not be parsed properly
|
# without this, xpect values like / \/zones\// will not be parsed properly
|
||||||
"(#{expectation.inspect})"
|
"(#{expectation.inspect})"
|
||||||
else
|
else
|
||||||
' ' + expectation.inspect
|
" " + expectation.inspect
|
||||||
end
|
end
|
||||||
format('%s { should%s %s%s }', itsy, naughty, matcher, xpect)
|
format("%s { should%s %s%s }", itsy, naughty, matcher, xpect)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -82,8 +82,8 @@ module Inspec
|
||||||
vars += "\n" unless vars.empty?
|
vars += "\n" unless vars.empty?
|
||||||
|
|
||||||
objarr = @qualifier
|
objarr = @qualifier
|
||||||
objarr = [['unknown object'.inspect]] if objarr.nil? || objarr.empty?
|
objarr = [["unknown object".inspect]] if objarr.nil? || objarr.empty?
|
||||||
obj = objarr.map { |q| ruby_qualifier(q) }.join('.')
|
obj = objarr.map { |q| ruby_qualifier(q) }.join(".")
|
||||||
|
|
||||||
rbtests = tests.map(&:to_ruby).join("\n ")
|
rbtests = tests.map(&:to_ruby).join("\n ")
|
||||||
format("%sdescribe %s do\n %s\nend", vars, obj, rbtests)
|
format("%sdescribe %s do\n %s\nend", vars, obj, rbtests)
|
||||||
|
|
|
@ -10,7 +10,7 @@ module Inspec
|
||||||
|
|
||||||
def add_test(t = nil)
|
def add_test(t = nil)
|
||||||
t ||= Test.new
|
t ||= Test.new
|
||||||
t.qualifier[0] = ['entry']
|
t.qualifier[0] = ["entry"]
|
||||||
@tests.push(t)
|
@tests.push(t)
|
||||||
t
|
t
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'inspec/utils/deprecation'
|
require "inspec/utils/deprecation"
|
||||||
|
|
||||||
# For backwards compatibility during the rename (see #3802),
|
# For backwards compatibility during the rename (see #3802),
|
||||||
# maintain the Inspec::Attribute namespace for people checking for
|
# maintain the Inspec::Attribute namespace for people checking for
|
||||||
|
@ -42,7 +42,7 @@ module Inspec
|
||||||
properties.each do |prop_name, prop_value|
|
properties.each do |prop_name, prop_value|
|
||||||
if EVENT_PROPERTIES.include? prop_name
|
if EVENT_PROPERTIES.include? prop_name
|
||||||
# OK, save the property
|
# OK, save the property
|
||||||
send((prop_name.to_s + '=').to_sym, prop_value)
|
send((prop_name.to_s + "=").to_sym, prop_value)
|
||||||
else
|
else
|
||||||
raise "Unrecognized property to Input::Event: #{prop_name}"
|
raise "Unrecognized property to Input::Event: #{prop_name}"
|
||||||
end
|
end
|
||||||
|
@ -60,7 +60,7 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def diagnostic_string
|
def diagnostic_string
|
||||||
to_h.reject { |_, val| val.nil? }.to_a.map { |pair| "#{pair[0]}: '#{pair[1]}'" }.join(', ')
|
to_h.reject { |_, val| val.nil? }.to_a.map { |pair| "#{pair[0]}: '#{pair[1]}'" }.join(", ")
|
||||||
end
|
end
|
||||||
|
|
||||||
def to_h
|
def to_h
|
||||||
|
@ -71,7 +71,7 @@ module Inspec
|
||||||
|
|
||||||
def self.probe_stack
|
def self.probe_stack
|
||||||
frames = caller_locations(2, 40)
|
frames = caller_locations(2, 40)
|
||||||
frames.reject! { |f| f.path && f.path.include?('/lib/inspec/') }
|
frames.reject! { |f| f.path && f.path.include?("/lib/inspec/") }
|
||||||
frames.first
|
frames.first
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -87,11 +87,13 @@ module Inspec
|
||||||
@name = name
|
@name = name
|
||||||
|
|
||||||
# output warn message if we are in a exec call
|
# output warn message if we are in a exec call
|
||||||
Inspec::Log.warn(
|
if Inspec::BaseCLI.inspec_cli_command == :exec
|
||||||
"Input '#{@name}' does not have a value. "\
|
Inspec::Log.warn(
|
||||||
"Use --input-file to provide a value for '#{@name}' or specify a "\
|
"Input '#{@name}' does not have a value. "\
|
||||||
"value with `attribute('#{@name}', value: 'somevalue', ...)`.",
|
"Use --input-file to provide a value for '#{@name}' or specify a "\
|
||||||
) if Inspec::BaseCLI.inspec_cli_command == :exec
|
"value with `attribute('#{@name}', value: 'somevalue', ...)`."
|
||||||
|
)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def method_missing(*_)
|
def method_missing(*_)
|
||||||
|
@ -222,7 +224,7 @@ module Inspec
|
||||||
provider: options[:provider] || :unknown,
|
provider: options[:provider] || :unknown,
|
||||||
priority: options[:priority] || Inspec::Input::DEFAULT_PRIORITY_FOR_UNKNOWN_CALLER,
|
priority: options[:priority] || Inspec::Input::DEFAULT_PRIORITY_FOR_UNKNOWN_CALLER,
|
||||||
file: location.path,
|
file: location.path,
|
||||||
line: location.lineno,
|
line: location.lineno
|
||||||
)
|
)
|
||||||
|
|
||||||
if options.key?(:default)
|
if options.key?(:default)
|
||||||
|
@ -255,7 +257,7 @@ module Inspec
|
||||||
action: :create,
|
action: :create,
|
||||||
provider: options[:provider],
|
provider: options[:provider],
|
||||||
file: loc.path,
|
file: loc.path,
|
||||||
line: loc.lineno,
|
line: loc.lineno
|
||||||
)
|
)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -287,7 +289,7 @@ module Inspec
|
||||||
priority: priority,
|
priority: priority,
|
||||||
value: new_value,
|
value: new_value,
|
||||||
file: location.path,
|
file: location.path,
|
||||||
line: location.lineno,
|
line: location.lineno
|
||||||
)
|
)
|
||||||
enforce_type_restriction!
|
enforce_type_restriction!
|
||||||
|
|
||||||
|
@ -318,7 +320,7 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def ruby_var_identifier
|
def ruby_var_identifier
|
||||||
identifier || 'attr_' + name.downcase.strip.gsub(/\s+/, '-').gsub(/[^\w-]/, '')
|
identifier || "attr_" + name.downcase.strip.gsub(/\s+/, "-").gsub(/[^\w-]/, "")
|
||||||
end
|
end
|
||||||
|
|
||||||
def to_ruby
|
def to_ruby
|
||||||
|
@ -330,7 +332,7 @@ module Inspec
|
||||||
# send the default: option as well. See #3759
|
# send the default: option as well. See #3759
|
||||||
res.push " default: #{value.inspect}," unless value.to_s.empty?
|
res.push " default: #{value.inspect}," unless value.to_s.empty?
|
||||||
res.push " description: '#{description}'," unless description.to_s.empty?
|
res.push " description: '#{description}'," unless description.to_s.empty?
|
||||||
res.push '})'
|
res.push "})"
|
||||||
res.join("\n")
|
res.join("\n")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -366,16 +368,16 @@ module Inspec
|
||||||
return unless has_value?
|
return unless has_value?
|
||||||
|
|
||||||
type_req = type
|
type_req = type
|
||||||
return if type_req == 'Any'
|
return if type_req == "Any"
|
||||||
|
|
||||||
proposed_value = current_value
|
proposed_value = current_value
|
||||||
|
|
||||||
invalid_type = false
|
invalid_type = false
|
||||||
if type_req == 'Regexp'
|
if type_req == "Regexp"
|
||||||
invalid_type = true if !valid_regexp?(proposed_value)
|
invalid_type = true if !valid_regexp?(proposed_value)
|
||||||
elsif type_req == 'Numeric'
|
elsif type_req == "Numeric"
|
||||||
invalid_type = true if !valid_numeric?(proposed_value)
|
invalid_type = true if !valid_numeric?(proposed_value)
|
||||||
elsif type_req == 'Boolean'
|
elsif type_req == "Boolean"
|
||||||
invalid_type = true if ![true, false].include?(proposed_value)
|
invalid_type = true if ![true, false].include?(proposed_value)
|
||||||
elsif proposed_value.is_a?(Module.const_get(type_req)) == false
|
elsif proposed_value.is_a?(Module.const_get(type_req)) == false
|
||||||
# TODO: why is this case here?
|
# TODO: why is this case here?
|
||||||
|
@ -396,8 +398,8 @@ module Inspec
|
||||||
|
|
||||||
type_req = type.capitalize
|
type_req = type.capitalize
|
||||||
abbreviations = {
|
abbreviations = {
|
||||||
'Num' => 'Numeric',
|
"Num" => "Numeric",
|
||||||
'Regex' => 'Regexp',
|
"Regex" => "Regexp",
|
||||||
}
|
}
|
||||||
type_req = abbreviations[type_req] if abbreviations.key?(type_req)
|
type_req = abbreviations[type_req] if abbreviations.key?(type_req)
|
||||||
if !VALID_TYPES.include?(type_req)
|
if !VALID_TYPES.include?(type_req)
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
module Inspec
|
module Inspec
|
||||||
class List < Value
|
class List < Value
|
||||||
def map
|
def map
|
||||||
raise 'Inspec::List.map needs to be called with a block' unless block_given?
|
raise "Inspec::List.map needs to be called with a block" unless block_given?
|
||||||
t = List.new
|
t = List.new
|
||||||
t.qualifier = [['x']]
|
t.qualifier = [["x"]]
|
||||||
yield(t)
|
yield(t)
|
||||||
return if t.qualifier == [['x']]
|
return if t.qualifier == [["x"]]
|
||||||
@qualifier.push(['map', "{ |x| #{t.to_ruby} }"])
|
@qualifier.push(["map", "{ |x| #{t.to_ruby} }"])
|
||||||
self
|
self
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -18,10 +18,10 @@ module Inspec
|
||||||
if @negated
|
if @negated
|
||||||
# We don't use the describe.one wrapper when negated because:
|
# We don't use the describe.one wrapper when negated because:
|
||||||
# !(test1 || test2) same as (!test1 && !test2) where && is implicit in inspec
|
# !(test1 || test2) same as (!test1 && !test2) where && is implicit in inspec
|
||||||
all_tests = @tests.map { |test|
|
all_tests = @tests.map do |test|
|
||||||
test.negate!
|
test.negate!
|
||||||
test
|
test
|
||||||
}.map(&:to_ruby).join("\n")
|
end.map(&:to_ruby).join("\n")
|
||||||
|
|
||||||
all_tests
|
all_tests
|
||||||
else
|
else
|
||||||
|
|
|
@ -3,10 +3,10 @@ module Inspec
|
||||||
def ruby_qualifier(q)
|
def ruby_qualifier(q)
|
||||||
if q.length <= 1
|
if q.length <= 1
|
||||||
q[0]
|
q[0]
|
||||||
elsif q[0] == 'map' && q.length == 2
|
elsif q[0] == "map" && q.length == 2
|
||||||
q[0] + ' ' + q[1]
|
q[0] + " " + q[1]
|
||||||
else
|
else
|
||||||
q[0] + '(' + q[1..-1].map(&:inspect).join(', ') + ')'
|
q[0] + "(" + q[1..-1].map(&:inspect).join(", ") + ")"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -41,17 +41,17 @@ module Inspec
|
||||||
return nil if @qualifier.empty?
|
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('.')
|
res = resource.map { |q| ruby_qualifier(q) }.join(".")
|
||||||
xres = nil
|
xres = nil
|
||||||
|
|
||||||
if @qualifier.length > 1
|
if @qualifier.length > 1
|
||||||
last = @qualifier[-1]
|
last = @qualifier[-1]
|
||||||
last_call = last.is_a?(Array) ? last[0].to_s : ''
|
last_call = last.is_a?(Array) ? last[0].to_s : ""
|
||||||
if last.length == 1 && last_call !~ /^to_.$/ && !last_call.include?('[') && !last_call.empty?
|
if last.length == 1 && last_call !~ /^to_.$/ && !last_call.include?("[") && !last_call.empty?
|
||||||
# this will go in its()
|
# this will go in its()
|
||||||
xres = last_call
|
xres = last_call
|
||||||
else
|
else
|
||||||
res += '.' + ruby_qualifier(last) unless last_call.empty?
|
res += "." + ruby_qualifier(last) unless last_call.empty?
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -63,15 +63,15 @@ module Inspec
|
||||||
vars = variables.map(&:to_ruby).join("\n")
|
vars = variables.map(&:to_ruby).join("\n")
|
||||||
vars += "\n" unless vars.empty?
|
vars += "\n" unless vars.empty?
|
||||||
res, xtra = describe_chain
|
res, xtra = describe_chain
|
||||||
itsy = xtra.nil? ? 'it' : 'its(' + xtra.to_s.inspect + ')'
|
itsy = xtra.nil? ? "it" : "its(" + xtra.to_s.inspect + ")"
|
||||||
naughty = @negated ? '_not' : ''
|
naughty = @negated ? "_not" : ""
|
||||||
xpect = if !defined?(@expectation)
|
xpect = if !defined?(@expectation)
|
||||||
''
|
""
|
||||||
elsif @expectation.class == Regexp
|
elsif @expectation.class == Regexp
|
||||||
# without this, xpect values like / \/zones\// will not be parsed properly
|
# without this, xpect values like / \/zones\// will not be parsed properly
|
||||||
"(#{@expectation.inspect})"
|
"(#{@expectation.inspect})"
|
||||||
elsif xpect != ''
|
elsif xpect != ""
|
||||||
' ' + expectation.inspect
|
" " + expectation.inspect
|
||||||
end
|
end
|
||||||
format("%s%sdescribe %s do\n %s { should%s %s%s }\nend",
|
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)
|
||||||
|
|
|
@ -12,12 +12,12 @@ module Inspec
|
||||||
end
|
end
|
||||||
|
|
||||||
def to_ruby
|
def to_ruby
|
||||||
res = @variable.nil? ? '' : "#{@variable} = "
|
res = @variable.nil? ? "" : "#{@variable} = "
|
||||||
res + @qualifier.map { |x| ruby_qualifier(x) }.join('.')
|
res + @qualifier.map { |x| ruby_qualifier(x) }.join(".")
|
||||||
end
|
end
|
||||||
|
|
||||||
def name_variable(cache = [])
|
def name_variable(cache = [])
|
||||||
@variable = Array('a'..'z').find { |x| !cache.include?(x) }
|
@variable = Array("a".."z").find { |x| !cache.include?(x) }
|
||||||
cache.push(@variable)
|
cache.push(@variable)
|
||||||
@variable
|
@variable
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,2 +1,2 @@
|
||||||
require 'inspec/plugin/v1/plugins'
|
require "inspec/plugin/v1/plugins"
|
||||||
require 'inspec/plugin/v1/registry'
|
require "inspec/plugin/v1/registry"
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'inspec/plugin/v1/registry'
|
require "inspec/plugin/v1/registry"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
module Plugins
|
module Plugins
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
require 'inspec/file_provider'
|
require "inspec/file_provider"
|
||||||
require 'inspec/plugin/v1/registry'
|
require "inspec/plugin/v1/registry"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
module Plugins
|
module Plugins
|
||||||
|
|
|
@ -41,7 +41,7 @@ module Inspec
|
||||||
# Even tho this is defined as an instance method, it gets added to
|
# Even tho this is defined as an instance method, it gets added to
|
||||||
# Inspec::Plugins::Resource via `extend`, so this is actually a class defintion.
|
# Inspec::Plugins::Resource via `extend`, so this is actually a class defintion.
|
||||||
def method_missing(method_name, *arguments, &block)
|
def method_missing(method_name, *arguments, &block)
|
||||||
require 'inspec/plugin/v2'
|
require "inspec/plugin/v2"
|
||||||
# Check to see if there is a resource_dsl plugin activator hook with the method name
|
# Check to see if there is a resource_dsl plugin activator hook with the method name
|
||||||
registry = Inspec::Plugin::V2::Registry.instance
|
registry = Inspec::Plugin::V2::Registry.instance
|
||||||
hook = registry.find_activators(plugin_type: :resource_dsl, activator_name: method_name).first
|
hook = registry.find_activators(plugin_type: :resource_dsl, activator_name: method_name).first
|
||||||
|
@ -146,7 +146,7 @@ module Inspec
|
||||||
|
|
||||||
# Warn if a resource pack is overwriting a core resource.
|
# Warn if a resource pack is overwriting a core resource.
|
||||||
# Suppress warning if the resource is an AWS resource, see #3822
|
# Suppress warning if the resource is an AWS resource, see #3822
|
||||||
if __resource_registry.key?(name) && !name.start_with?('aws_')
|
if __resource_registry.key?(name) && !name.start_with?("aws_")
|
||||||
Inspec::Log.warn("Overwriting resource #{name}. To reference a specific version of #{name} use the resource() method")
|
Inspec::Log.warn("Overwriting resource #{name}. To reference a specific version of #{name} use the resource() method")
|
||||||
end
|
end
|
||||||
__resource_registry[name] = cl
|
__resource_registry[name] = cl
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'inspec/plugin/v1/registry'
|
require "inspec/plugin/v1/registry"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
module Plugins
|
module Plugins
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'inspec/plugin/v1/registry'
|
require "inspec/plugin/v1/registry"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
module Plugins
|
module Plugins
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
require 'forwardable'
|
require "forwardable"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
# Resource Plugins
|
# Resource Plugins
|
||||||
# NOTE: the autoloading here is rendered moot by the fact that
|
# NOTE: the autoloading here is rendered moot by the fact that
|
||||||
# all core plugins are `require`'d by the base inspec.rb
|
# all core plugins are `require`'d by the base inspec.rb
|
||||||
module Plugins
|
module Plugins
|
||||||
autoload :Resource, 'inspec/plugin/v1/plugin_types/resource'
|
autoload :Resource, "inspec/plugin/v1/plugin_types/resource"
|
||||||
autoload :CLI, 'inspec/plugin/v1/plugin_types/cli'
|
autoload :CLI, "inspec/plugin/v1/plugin_types/cli"
|
||||||
autoload :Fetcher, 'inspec/plugin/v1/plugin_types/fetcher'
|
autoload :Fetcher, "inspec/plugin/v1/plugin_types/fetcher"
|
||||||
autoload :SourceReader, 'inspec/plugin/v1/plugin_types/source_reader'
|
autoload :SourceReader, "inspec/plugin/v1/plugin_types/source_reader"
|
||||||
autoload :Secret, 'inspec/plugin/v1/plugin_types/secret'
|
autoload :Secret, "inspec/plugin/v1/plugin_types/secret"
|
||||||
end
|
end
|
||||||
|
|
||||||
# PLEASE NOTE: The Plugin system is an internal mechanism for connecting
|
# PLEASE NOTE: The Plugin system is an internal mechanism for connecting
|
||||||
|
@ -26,24 +26,24 @@ module Inspec
|
||||||
@paths = []
|
@paths = []
|
||||||
|
|
||||||
# load plugins in the same gem installation
|
# load plugins in the same gem installation
|
||||||
lib_home = File.expand_path(File.join(__FILE__, '..', '..', '..', '..'))
|
lib_home = File.expand_path(File.join(__FILE__, "..", "..", "..", ".."))
|
||||||
@paths += Dir[lib_home+'/inspec-*-*/lib/inspec-*rb']
|
@paths += Dir[lib_home + "/inspec-*-*/lib/inspec-*rb"]
|
||||||
|
|
||||||
# traverse out of inspec-vX.Y.Z/lib/inspec/plugins.rb
|
# traverse out of inspec-vX.Y.Z/lib/inspec/plugins.rb
|
||||||
@home = home || File.join(Inspec.config_dir, 'plugins')
|
@home = home || File.join(Inspec.config_dir, "plugins")
|
||||||
@paths += Dir[File.join(@home, '**{,/*/**}', '*.gemspec')]
|
@paths += Dir[File.join(@home, "**{,/*/**}", "*.gemspec")]
|
||||||
.map { |x| File.dirname(x) }
|
.map { |x| File.dirname(x) }
|
||||||
.map { |x| Dir[File.join(x, 'lib', 'inspec-*.rb')] }
|
.map { |x| Dir[File.join(x, "lib", "inspec-*.rb")] }
|
||||||
.flatten
|
.flatten
|
||||||
|
|
||||||
# load bundled plugins
|
# load bundled plugins
|
||||||
bundled_dir = File.expand_path(File.dirname(__FILE__))
|
bundled_dir = File.expand_path(File.dirname(__FILE__))
|
||||||
@paths += Dir[File.join(bundled_dir, '..', 'bundles', 'inspec-*.rb')].flatten
|
@paths += Dir[File.join(bundled_dir, "..", "bundles", "inspec-*.rb")].flatten
|
||||||
|
|
||||||
# map paths to names
|
# map paths to names
|
||||||
@registry = Hash[@paths.map { |x|
|
@registry = Hash[@paths.map do |x|
|
||||||
[File.basename(x, '.rb'), x]
|
[File.basename(x, ".rb"), x]
|
||||||
}]
|
end]
|
||||||
end
|
end
|
||||||
|
|
||||||
def load(name)
|
def load(name)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'inspec/errors'
|
require "inspec/errors"
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
module Plugin
|
module Plugin
|
||||||
|
@ -23,20 +23,20 @@ module Inspec
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
require 'inspec/globals'
|
require "inspec/globals"
|
||||||
require 'inspec/plugin/v2/config_file'
|
require "inspec/plugin/v2/config_file"
|
||||||
require 'inspec/plugin/v2/registry'
|
require "inspec/plugin/v2/registry"
|
||||||
require 'inspec/plugin/v2/loader'
|
require "inspec/plugin/v2/loader"
|
||||||
require 'inspec/plugin/v2/plugin_base'
|
require "inspec/plugin/v2/plugin_base"
|
||||||
|
|
||||||
# Load all plugin type base classes
|
# Load all plugin type base classes
|
||||||
Dir.glob(File.join(__dir__, 'v2', 'plugin_types', '*.rb')).each { |file| require file }
|
Dir.glob(File.join(__dir__, "v2", "plugin_types", "*.rb")).each { |file| require file }
|
||||||
|
|
||||||
module Inspec
|
module Inspec
|
||||||
# Provides the base class that plugin implementors should use.
|
# Provides the base class that plugin implementors should use.
|
||||||
def self.plugin(version, plugin_type = nil)
|
def self.plugin(version, plugin_type = nil)
|
||||||
unless version == 2
|
unless version == 2
|
||||||
raise 'Only plugins version 2 is supported!'
|
raise "Only plugins version 2 is supported!"
|
||||||
end
|
end
|
||||||
|
|
||||||
return Inspec::Plugin::V2::PluginBase if plugin_type.nil?
|
return Inspec::Plugin::V2::PluginBase if plugin_type.nil?
|
||||||
|
|
|
@ -6,7 +6,7 @@ module Inspec::Plugin::V2
|
||||||
:activated?,
|
:activated?,
|
||||||
:exception,
|
:exception,
|
||||||
:activation_proc,
|
:activation_proc,
|
||||||
:implementation_class,
|
:implementation_class
|
||||||
) do
|
) do
|
||||||
def initialize(*)
|
def initialize(*)
|
||||||
super
|
super
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
require 'json'
|
require "json"
|
||||||
|
|
||||||
module Inspec::Plugin::V2
|
module Inspec::Plugin::V2
|
||||||
# Represents the plugin config file on disk.
|
# Represents the plugin config file on disk.
|
||||||
|
@ -17,7 +17,7 @@ module Inspec::Plugin::V2
|
||||||
# Returns the defaut path for a config file.
|
# Returns the defaut path for a config file.
|
||||||
# This respects ENV['INSPEC_CONFIG_DIR'].
|
# This respects ENV['INSPEC_CONFIG_DIR'].
|
||||||
def self.default_path
|
def self.default_path
|
||||||
File.join(Inspec.config_dir, 'plugins.json')
|
File.join(Inspec.config_dir, "plugins.json")
|
||||||
end
|
end
|
||||||
|
|
||||||
# Implement Enumerable. All Enumerable methds act
|
# Implement Enumerable. All Enumerable methds act
|
||||||
|
@ -40,7 +40,7 @@ module Inspec::Plugin::V2
|
||||||
# Add an entry with full validation.
|
# Add an entry with full validation.
|
||||||
def add_entry(proposed_entry)
|
def add_entry(proposed_entry)
|
||||||
unless proposed_entry.keys.all? { |field| field.is_a? Symbol }
|
unless proposed_entry.keys.all? { |field| field.is_a? Symbol }
|
||||||
raise Inspec::Plugin::V2::ConfigError, 'All keys to ConfigFile#add_entry must be symbols'
|
raise Inspec::Plugin::V2::ConfigError, "All keys to ConfigFile#add_entry must be symbols"
|
||||||
end
|
end
|
||||||
|
|
||||||
validate_entry(proposed_entry)
|
validate_entry(proposed_entry)
|
||||||
|
@ -71,7 +71,7 @@ module Inspec::Plugin::V2
|
||||||
|
|
||||||
def blank_structure
|
def blank_structure
|
||||||
{
|
{
|
||||||
plugins_config_version: '1.0.0',
|
plugins_config_version: "1.0.0",
|
||||||
plugins: [],
|
plugins: [],
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
@ -88,7 +88,7 @@ module Inspec::Plugin::V2
|
||||||
raise Inspec::Plugin::V2::ConfigError, "Missing 'plugins_config_version' entry at #{path} - currently support versions: 1.0.0"
|
raise Inspec::Plugin::V2::ConfigError, "Missing 'plugins_config_version' entry at #{path} - currently support versions: 1.0.0"
|
||||||
end
|
end
|
||||||
|
|
||||||
unless @data[:plugins_config_version] == '1.0.0'
|
unless @data[:plugins_config_version] == "1.0.0"
|
||||||
raise Inspec::Plugin::V2::ConfigError, "Unsupported plugins.json file version #{@data[:plugins_config_version]} at #{path} - currently support versions: 1.0.0"
|
raise Inspec::Plugin::V2::ConfigError, "Unsupported plugins.json file version #{@data[:plugins_config_version]} at #{path} - currently support versions: 1.0.0"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -106,7 +106,7 @@ module Inspec::Plugin::V2
|
||||||
validate_entry(plugin_entry)
|
validate_entry(plugin_entry)
|
||||||
rescue Inspec::Plugin::V2::ConfigError => ex
|
rescue Inspec::Plugin::V2::ConfigError => ex
|
||||||
# append some context to the message
|
# append some context to the message
|
||||||
raise Inspec::Plugin::V2::ConfigError, 'Malformed plugins.json file - ' + ex.message + " at index #{idx}"
|
raise Inspec::Plugin::V2::ConfigError, "Malformed plugins.json file - " + ex.message + " at index #{idx}"
|
||||||
end
|
end
|
||||||
|
|
||||||
# Check for duplicates
|
# Check for duplicates
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue