Class: Inspec::Profile

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/inspec/profile.rb,
lib/inspec/utils/profile_ast_helpers.rb

Defined Under Namespace

Classes: AstHelper

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_reader, options = {}) ⇒ Profile

rubocop:disable Metrics/AbcSize



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/inspec/profile.rb', line 94

def initialize(source_reader, options = {})
  @source_reader = source_reader
  @target = options[:target]
  @logger = options[:logger] || Logger.new(nil)
  @locked_dependencies = options[:dependencies]
  @controls = options[:controls] || []
  @tags = options[:tags] || []
  @writable = options[:writable] || false
  @profile_id = options[:id]
  @profile_name = options[:profile_name]
  @cache = options[:vendor_cache] || Cache.new
  @input_values = options[:inputs]
  @tests_collected = false
  @libraries_loaded = false
  @state = :loaded
  @check_mode = options[:check_mode] || false
  @parent_profile = options[:parent_profile]
  @legacy_profile_path = options[:profiles_path] || false
  @check_cookstyle = options[:with_cookstyle]
  .finalize(@source_reader., @profile_id, options)

  # if a backend has already been created, clone it so each profile has its own unique backend object
  # otherwise, create a new backend object
  #
  # This is necessary since we store the RuntimeProfile on the backend object. If a user runs `inspec exec`
  # with multiple profiles, only the RuntimeProfile for the last-loaded profile will be available if
  # we share the backend between profiles.
  #
  # This will cause issues if a profile attempts to load a file via `inspec.profile.file`
  train_options = options.reject { |k, _| k == "target" } # See https://github.com/chef/inspec/pull/1646
  @backend = options[:backend].nil? ? Inspec::Backend.create(Inspec::Config.new(train_options)) : options[:backend].dup
  @runtime_profile = RuntimeProfile.new(self)
  @backend.profile = @runtime_profile

  # The AttributeRegistry is in charge of keeping track of inputs;
  # it is the single source of truth. Now that we have a profile object,
  # we can create any inputs that were provided by various mechanisms.
  options[:runner_conf] ||= Inspec::Config.cached

  # Catch legacy CLI input option usage
  if options[:runner_conf].key?(:attrs)
    Inspec.deprecate(:rename_attributes_to_inputs, "Use --input-file on the command line instead of --attrs.")
    options[:runner_conf][:input_file] = options[:runner_conf].delete(:attrs)
  elsif options[:runner_conf].key?(:input_files)
    # The kitchen-inspec docs say to use plural. Our CLI and internal expectations are singular.
    options[:runner_conf][:input_file] = options[:runner_conf].delete(:input_files)
  end

  # Catch legacy kitchen-inspec input usage
  if options[:runner_conf].key?(:attributes)
    Inspec.deprecate(:rename_attributes_to_inputs, "Use :inputs in your kitchen.yml verifier config instead of :attributes.")
    options[:runner_conf][:inputs] = options[:runner_conf].delete(:attributes)
  end

  Inspec::InputRegistry.bind_profile_inputs(
    # Every input only exists in the context of a profile
    .params[:name], # TODO: test this with profile aliasing
    # Remaining args are possible sources of inputs
    cli_input_files: options[:runner_conf][:input_file], # From CLI --input-file
    profile_metadata: ,
    runner_api: options[:runner_conf][:inputs], # This is the route the audit_cookbook and kitchen-inspec take
    cli_input_arg: options[:runner_conf][:input] # The --input name=value CLI option
  )

  @runner_context =
    options[:profile_context] ||
    Inspec::ProfileContext.for_profile(self, @backend)

  if .supports_platform?(@backend)
    @supports_platform = true
  else
    @supports_platform = false
    @state = :skipped
  end
  @supports_runtime = .supports_runtime?
end

Instance Attribute Details

#backendObject (readonly)

Returns the value of attribute backend.



87
88
89
# File 'lib/inspec/profile.rb', line 87

def backend
  @backend
end

#check_modeObject (readonly)

Returns the value of attribute check_mode.



87
88
89
# File 'lib/inspec/profile.rb', line 87

def check_mode
  @check_mode
end

#parent_profileObject

Returns the value of attribute parent_profile.



88
89
90
# File 'lib/inspec/profile.rb', line 88

def parent_profile
  @parent_profile
end

#profile_idObject

Returns the value of attribute profile_id.



88
89
90
# File 'lib/inspec/profile.rb', line 88

def profile_id
  @profile_id
end

#profile_nameObject

Returns the value of attribute profile_name.



88
89
90
# File 'lib/inspec/profile.rb', line 88

def profile_name
  @profile_name
end

#runner_contextObject (readonly)

Returns the value of attribute runner_context.



87
88
89
# File 'lib/inspec/profile.rb', line 87

def runner_context
  @runner_context
end

#source_readerObject (readonly)

Returns the value of attribute source_reader.



87
88
89
# File 'lib/inspec/profile.rb', line 87

def source_reader
  @source_reader
end

#targetObject

Returns the value of attribute target.



88
89
90
# File 'lib/inspec/profile.rb', line 88

def target
  @target
end

Class Method Details

.copy_deps_into_cache(file_provider, opts) ⇒ Object

Check if the profile contains a vendored cache, move content into global cache TODO: use relative file provider TODO: use source reader for Cache as well



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/inspec/profile.rb', line 35

def self.copy_deps_into_cache(file_provider, opts)
  # filter content
  cache = file_provider.files.find_all do |entry|
    entry.start_with?("vendor")
  end
  content = Hash[cache.map { |x| [x, file_provider.binread(x)] }]
  keys = content.keys
  keys.each do |key|
    next if content[key].nil?

    # remove prefix
    rel = Pathname.new(key).relative_path_from(Pathname.new("vendor")).to_s
    tar = Pathname.new(opts[:vendor_cache].path).join(rel)

    FileUtils.mkdir_p tar.dirname.to_s
    Inspec::Log.debug "Copy #{tar} to cache directory"
    File.binwrite(tar.to_s, content[key])
  end
end

.for_fetcher(fetcher, config) ⇒ Object



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

def self.for_fetcher(fetcher, config)
  opts = config.respond_to?(:final_options) ? config.final_options : config
  opts[:vendor_cache] = opts[:vendor_cache] || Cache.new
  path, writable = fetcher.fetch
  for_path(path, opts.merge(target: fetcher.target, writable: writable))
end

.for_path(path, opts) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/inspec/profile.rb', line 55

def self.for_path(path, opts)
  file_provider = FileProvider.for_path(path)
  rp = file_provider.relative_provider

  # copy embedded dependencies into global cache
  copy_deps_into_cache(rp, opts) unless opts[:vendor_cache].nil?

  reader = Inspec::SourceReader.resolve(rp)
  if reader.nil?
    raise("Don't understand inspec profile in #{path}, it " \
         "doesn't look like a supported profile structure.")
  end
  new(reader, opts)
end

.for_target(target, opts = {}) ⇒ Object



77
78
79
80
81
82
83
84
85
# File 'lib/inspec/profile.rb', line 77

def self.for_target(target, opts = {})
  opts[:vendor_cache] ||= Cache.new
  config = {}
  unless opts[:runner_conf].nil?
    config = opts[:runner_conf].respond_to?(:final_options) ? opts[:runner_conf].final_options : opts[:runner_conf]
  end
  fetcher = resolve_target(target, opts[:vendor_cache], config)
  for_fetcher(fetcher, opts)
end

.resolve_target(target, cache, opts = {}) ⇒ Object



27
28
29
30
# File 'lib/inspec/profile.rb', line 27

def self.resolve_target(target, cache, opts = {})
  Inspec::Log.debug "Resolve #{target} into cache #{cache.path}"
  Inspec::CachedFetcher.new(target, cache, opts)
end

Instance Method Details

#activate_plugin_if_gem_basedObject

InSpec 7 introduced gem-based resource packs, so some “profiles” are now gem-based In this case, they are backed by a gem that contains an inspec.yml and a lib/PATH/plugin.rb which contains activator code which needs to be fired.



406
407
408
409
410
411
# File 'lib/inspec/profile.rb', line 406

def activate_plugin_if_gem_based
  return unless source_reader.is_a?(SourceReaders::GemReader)

  reg = Inspec::Plugin::V2::Registry.instance
  reg.find_activator(plugin_name: name.to_sym).activate!
end

#archive(opts) ⇒ Object

generates a archive of a folder profile



1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
# File 'lib/inspec/profile.rb', line 1063

def archive(opts)
  # check if file exists otherwise overwrite the archive
  dst = archive_name(opts)
  if dst.exist? && !opts[:overwrite]
    @logger.info "Archive #{dst} exists already. Use --overwrite."
    return false
  end

  # remove existing archive
  FileUtils.rm_f(dst) if dst.exist?
  @logger.info "Generate archive #{dst}."

  # filter files that should not be part of the profile
  # TODO ignore all .files, but add the files to debug output

  # Generate temporary inspec.json for archive
  export_opt_enabled = opts[:export] || opts[:legacy_export]
  if export_opt_enabled
    info_for_profile_summary = opts[:legacy_export] ? info : info_from_parse
    Inspec::Utils::JsonProfileSummary.produce_json(
      info: info_for_profile_summary,
      write_path: "#{root_path}inspec.json",
      suppress_output: true
    )
  end

  # display all files that will be part of the archive
  @logger.debug "Add the following files to archive:"
  files.each { |f| @logger.debug "    " + f }
  @logger.debug "    inspec.json" if export_opt_enabled

  archive_files = export_opt_enabled ? files.push("inspec.json") : files
  if opts[:zip]
    # generate zip archive
    require "inspec/archive/zip"
    zag = Inspec::Archive::ZipArchiveGenerator.new
    zag.archive(root_path, archive_files, dst)
  else
    # generate tar archive
    require "inspec/archive/tar"
    tag = Inspec::Archive::TarArchiveGenerator.new
    tag.archive(root_path, archive_files, dst)
  end

  # Cleanup
  FileUtils.rm_f("#{root_path}inspec.json") if export_opt_enabled

  @logger.info "Finished archive generation."
  true
end

#checkBoolean

Check if the profile is internally well-structured. The logger will be used to print information on errors and warnings which are found.

Returns:

  • (Boolean)

    true if no errors were found, false otherwise



868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
# File 'lib/inspec/profile.rb', line 868

def check # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength
  # initial values for response object
  result = {
    summary: {
      valid: false,
      timestamp: Time.now.iso8601,
      location: @target,
      profile: nil,
      controls: 0,
    },
    errors: [],
    warnings: [],
    offenses: [],
  }

  # memoize `info_from_parse` with tests
  info_from_parse(include_tests: true)

  entry = lambda { |file, line, column, control, msg|
    {
      file: file,
      line: line,
      column: column,
      control_id: control,
      msg: msg,
    }
  }

  warn = lambda { |file, line, column, control, msg|
    @logger.warn(msg)
    result[:warnings].push(entry.call(file, line, column, control, msg))
  }

  error = lambda { |file, line, column, control, msg|
    @logger.error(msg)
    result[:errors].push(entry.call(file, line, column, control, msg))
  }

  offense = lambda { |file, line, column, control, msg|
    result[:offenses].push(entry.call(file, line, column, control, msg))
  }

  @logger.info "Checking profile in #{@target}"
  meta_path = @source_reader.target.abs_path(@source_reader..ref)

  # verify metadata
  m_errors, m_warnings = validity_check
  m_errors.each { |msg| error.call(meta_path, 0, 0, nil, msg) }
  m_warnings.each { |msg| warn.call(meta_path, 0, 0, nil, msg) }
  m_unsupported = .unsupported
  m_unsupported.each { |u| warn.call(meta_path, 0, 0, nil, "doesn't support: #{u}") }
  @logger.info "Metadata OK." if m_errors.empty? && m_unsupported.empty?

  # only run the vendor check if the legacy profile-path is not used as argument
  if @legacy_profile_path == false
    # verify that a lockfile is present if we have dependencies
    unless .dependencies.empty?
      error.call(meta_path, 0, 0, nil, "Your profile needs to be vendored with `inspec vendor`.") unless lockfile_exists?
    end

    if lockfile_exists?
      # verify if metadata and lockfile are out of sync
      if lockfile.deps.size != .dependencies.size
        error.call(meta_path, 0, 0, nil, "inspec.yml and inspec.lock are out-of-sync. Please re-vendor with `inspec vendor`.")
      end

      # verify if metadata and lockfile have the same dependency names
      .dependencies.each do |dep|
        # Skip if the dependency does not specify a name
        next if dep[:name].nil?

        # TODO: should we also verify that the soure is the same?
        unless lockfile.deps.map { |x| x[:name] }.include? dep[:name]
          error.call(meta_path, 0, 0, nil, "Cannot find #{dep[:name]} in lockfile. Please re-vendor with `inspec vendor`.")
        end
      end
    end
  end

  # extract profile name
  result[:summary][:profile] = info_from_parse[:name]

  count = info_from_parse[:controls].count
  result[:summary][:controls] = count
  if count == 0
    warn.call(nil, nil, nil, nil, "No controls or tests were defined.")
  else
    @logger.info("Found #{count} controls.")
  end

  # iterate over hash of groups
  info_from_parse[:controls].each do |control|
    sfile = control[:source_location][:ref]
    sline = control[:source_location][:line]
    id = control[:id]
    error.call(sfile, sline, nil, id, "Avoid controls with empty IDs") if id.nil? || id.empty?
    next if id.start_with? "(generated "

    warn.call(sfile, sline, nil, id, "Control #{id} has no title") if control[:title].to_s.empty?
    warn.call(sfile, sline, nil, id, "Control #{id} has no descriptions") if control[:descriptions][:default].to_s.empty?
    warn.call(sfile, sline, nil, id, "Control #{id} has impact > 1.0") if control[:impact].to_f > 1.0
    warn.call(sfile, sline, nil, id, "Control #{id} has impact < 0.0") if control[:impact].to_f < 0.0
    warn.call(sfile, sline, nil, id, "Control #{id} has no tests defined") if control[:checks].nil? || control[:checks].empty?
  end

  # Running cookstyle to check for code offenses
  if @check_cookstyle
    cookstyle_linting_check.each do |lint_output|
      data = lint_output.split(":")
      msg = "#{data[-2]}:#{data[-1]}"
      offense.call(data[0], data[1], data[2], nil, msg)
    end
  end
  # profile is valid if we could not find any error & offenses
  result[:summary][:valid] = result[:errors].empty? && result[:offenses].empty?

  @logger.info "Control definitions OK." if result[:warnings].empty?
  result
end

#collect_gem_dependenciesObject

This collects the gem dependencies data from parent and its dependent profiles



450
451
452
453
454
455
456
457
458
459
460
# File 'lib/inspec/profile.rb', line 450

def collect_gem_dependencies
  gem_dependencies = []
  # This collects the dependent profiles gem dependencies if any
  locked_dependencies.dep_list.each do |_name, dep|
    profile = dep.profile
    gem_dependencies << profile..gem_dependencies unless profile..gem_dependencies.empty?
  end
  # Appends the parent profile gem dependencies which are available through metadata
  gem_dependencies << .gem_dependencies unless .gem_dependencies.empty?
  gem_dependencies.flatten.uniq
end

#collect_testsObject



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/inspec/profile.rb', line 247

def collect_tests
  unless @tests_collected || failed?

    # This is that one common place in InSpec engine which is used to collect tests of InSpec profile
    # One common place used by most of the CLI commands using profile, like exec, export etc
    # Checking for profile signature in parent profile only
    # Child profiles of a signed profile are extracted to cache dir
    # Hence they are not in .iaf format
    # Only runs this block when preview flag CHEF_PREVIEW_MANDATORY_PROFILE_SIGNING is set
    Inspec.with_feature("inspec-mandatory-profile-signing") {
      if !parent_profile && !virtual_profile?
        cfg = Inspec::Config.cached
        if cfg.is_a?(Inspec::Config) && !cfg.allow_unsigned_profiles?
          raise Inspec::ProfileSignatureRequired, "Signature required for profile: #{name}. Please provide a signed profile. Or set CHEF_ALLOW_UNSIGNED_PROFILES in the environment. Or use `--allow-unsigned-profiles` flag with InSpec CLI." unless verify_if_signed
        end
      end
    }

    return unless supports_platform?

    locked_dependencies.each(&:collect_tests)

    tests = filter_waived_controls

    # Collect tests
    tests.each do |path, content|
      next if content.nil? || content.empty?

      abs_path = source_reader.target.abs_path(path)
      begin
        @runner_context.load_control_file(content, abs_path, nil)
      rescue => e
        @state = :failed
        raise Inspec::Exceptions::ProfileLoadFailed, "Failed to load source for #{path}: #{e}"
      end
    end
    @tests_collected = true
  end
  @runner_context.all_rules
end

#cookstyle_linting_checkObject



709
710
711
712
713
714
715
716
# File 'lib/inspec/profile.rb', line 709

def cookstyle_linting_check
  msgs = []
  return msgs if Inspec.locally_windows? # See #5723

  output = cookstyle_rake_output.split("Offenses:").last
  msgs = output.split("\n").select { |x| x =~ /[A-Z]:/ } unless output.nil?
  msgs
end

#cookstyle_rake_outputObject

Cookstyle linting rake run output



719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
# File 'lib/inspec/profile.rb', line 719

def cookstyle_rake_output
  require "cookstyle"
  require "rubocop/rake_task"
  begin
    RuboCop::RakeTask.new(:cookstyle_lint) do |spec|
      spec.options += [
        "--display-cop-names",
        "--parallel",
        "--only=InSpec/Deprecations",
      ]
      spec.patterns += Dir.glob("#{@target}/**/*.rb").reject { |f| File.directory?(f) }
      spec.fail_on_error = false
    end
  rescue LoadError
    puts "Rubocop is not available. Install the rubocop gem to run the lint tests."
  end
  begin
    stdout = StringIO.new
    $stdout = stdout
    Rake::Task["cookstyle_lint"].invoke
    $stdout = STDOUT
    Rake.application["cookstyle_lint"].reenable
    stdout.string
  rescue => e
    puts "Cookstyle lint checks could not be performed. Error while running cookstyle - #{e}"
    ""
  end
end

#cwdObject

TODO(ssd): Relative path handling really needs to be carefully thought through, especially with respect to relative paths in tarballs.



1147
1148
1149
# File 'lib/inspec/profile.rb', line 1147

def cwd
  @target.is_a?(String) && File.directory?(@target) ? @target : "./"
end

#failed?Boolean

Returns:

  • (Boolean)


183
184
185
# File 'lib/inspec/profile.rb', line 183

def failed?
  @state == :failed
end

#filesObject



1130
1131
1132
# File 'lib/inspec/profile.rb', line 1130

def files
  @source_reader.target.files
end

#filter_controls_by_id_and_tags(controls) ⇒ Object



665
666
667
668
669
670
671
# File 'lib/inspec/profile.rb', line 665

def filter_controls_by_id_and_tags(controls)
  controls.select do |control|
    tag_ids = get_all_tags_list(control[:tags])
    (include_controls_list.empty? || include_controls_list.any? { |control_id| control_id.match?(control[:id]) }) &&
      (include_tags_list.empty? || include_tags_list.any? { |tag_id| tag_ids.any? { |tag| tag_id.match?(tag) } })
  end
end

#filter_waived_controlsObject

Wipe out waived controls



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/inspec/profile.rb', line 289

def filter_waived_controls
  cfg = Inspec::Config.cached
  return tests unless cfg["filter_waived_controls"]

  ## Find the waivers file
  # - TODO: cli_opts and instance_variable_get could be exposed
  waiver_paths = cfg.instance_variable_get(:@cli_opts)["waiver_file"]
  if waiver_paths.nil? || waiver_paths.empty?
    Inspec::Log.error "Must use --waiver-file with --filter-waived-controls"
    Inspec::UI.new.exit(:usage_error)
  end

  # # Pull together waiver
  waived_control_ids = []
  waiver_paths.each do |waiver_path|
    # Ruby 3.1 treats YAML load as a dangerous operation by default, requiring us to declare date and time classes as permitted
    # It's not a valid option in 3.0.x
    if Gem.ruby_version >= Gem::Version.new("3.1.0")
      waiver_content = ::YAML.load_file(waiver_path, permitted_classes: [Date, Time])
    else
      waiver_content = YAML.load_file(waiver_path)
    end

    unless waiver_content
      # Note that we will have already issued a detailed warning
      Inspec::Log.error "YAML parsing error in #{waiver_path}"
      Inspec::UI.new.exit(:usage_error)
    end
    waived_control_ids << waiver_content.keys
  end
  waived_control_id_regex = "(#{waived_control_ids.join("|")})"

  ## Purge tests (this could be doone in next block for performance)
  ## TODO: implement earlier with pure AST and pure autocorrect AST
  filtered_tests = {}
  if cfg["retain_waiver_data"]
    # VERY EXPERIMENTAL, but an empty describe block at the top level
    # of the control blocks evaluation of ruby code until later-term
    # waivers (behind the scenes this tells RSpec to hold on and use its internals to lazy load the code). This allows current waiver-data (e.g. skips) to still
    # be processed and rendered
    tests.each do |control_filename, source_code|
      cleared_tests = source_code.scan(/control\s+['"].+?['"].+?(?=(?:control\s+['"].+?['"])|\z)/m).collect do |element|
        next if element.nil? || element.empty?

        if element&.match?(waived_control_id_regex)
          splitlines = element.split("\n")
          splitlines[0] + "\ndescribe '---' do\n" + splitlines[1..-1].join("\n") + "\nend\n"
        else
          element
        end
      end.join("")
      filtered_tests[control_filename] = cleared_tests
    end
  else
    tests.each do |control_filename, source_code|
      cleared_tests = source_code.scan(/control\s+['"].+?['"].+?(?=(?:control\s+['"].+?['"])|\z)/m).select do |control_code|
        !control_code.match?(waived_control_id_regex)
      end.join("")

      filtered_tests[control_filename] = cleared_tests
    end
  end
  filtered_tests
end

#generate_lockfileInspec::Lockfile

Generate an in-memory lockfile. This won’t render the lock file to disk, it must be explicitly written to disk by the caller.

Parameters:

  • vendor_path (String)

    Path to the on-disk vendor dir

Returns:



1166
1167
1168
1169
1170
# File 'lib/inspec/profile.rb', line 1166

def generate_lockfile
  res = Inspec::DependencySet.new(cwd, @cache, nil, @backend)
  res.vendor(.dependencies)
  Inspec::Lockfile.from_dependency_set(res)
end

#get_all_tags_list(control_tags) ⇒ Object



673
674
675
676
677
678
679
680
681
# File 'lib/inspec/profile.rb', line 673

def get_all_tags_list(control_tags)
  all_tags = []
  control_tags.each do |tags|
    all_tags.push(tags)
  end
  all_tags.flatten.compact.uniq.map(&:to_s)
rescue
  []
end

#include_controls_listObject

This creates the list of controls provided in the –controls options which need to be include for evaluation.



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/inspec/profile.rb', line 356

def include_controls_list
  return [] if @controls.nil? || @controls.empty?

  included_controls = @controls
  # Check for anything that might be a regex in the list, and make it official
  included_controls.each_with_index do |inclusion, index|
    next if inclusion.is_a?(Regexp)
    # Insist the user wrap the regex in slashes to demarcate it as a regex
    next unless inclusion.start_with?("/") && inclusion.end_with?("/")

    inclusion = inclusion[1..-2] # Trim slashes
    begin
      re = Regexp.new(inclusion)
      included_controls[index] = re
    rescue RegexpError => e
      warn "Ignoring unparseable regex '/#{inclusion}/' in --control CLI option: #{e.message}"
      included_controls[index] = nil
    end
  end
  included_controls.compact!
  included_controls
end

#include_group_data?(group_data) ⇒ Boolean

Returns:

  • (Boolean)


683
684
685
686
687
688
689
690
691
692
693
# File 'lib/inspec/profile.rb', line 683

def include_group_data?(group_data)
  unless include_controls_list.empty?
    # {:id=>"controls/example-tmp.rb", :title=>"/ profile", :controls=>["tmp-1.0"]}
    # Check if the group should be included based on the controls it contains
    group_data[:controls].any? do |control_id|
      include_controls_list.any? { |id| id.match?(control_id) }
    end
  else
    true
  end
end

#include_tags_listObject

This creates the list of controls to be filtered by tag values provided in the –tags options



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/inspec/profile.rb', line 380

def include_tags_list
  return [] if @tags.nil? || @tags.empty?

  included_tags = @tags
  # Check for anything that might be a regex in the list, and make it official
  included_tags.each_with_index do |inclusion, index|
    next if inclusion.is_a?(Regexp)
    # Insist the user wrap the regex in slashes to demarcate it as a regex
    next unless inclusion.start_with?("/") && inclusion.end_with?("/")

    inclusion = inclusion[1..-2] # Trim slashes
    begin
      re = Regexp.new(inclusion)
      included_tags[index] = re
    rescue RegexpError => e
      warn "Ignoring unparseable regex '/#{inclusion}/' in --control CLI option: #{e.message}"
      included_tags[index] = nil
    end
  end
  included_tags.compact!
  included_tags
end

#info(res = params.dup) ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength



519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
# File 'lib/inspec/profile.rb', line 519

def info(res = params.dup) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength
  # add information about the controls
  res[:controls] = res[:controls].map do |id, rule|
    next if id.to_s.empty?

    data = rule.dup
    data.delete(:checks)
    data[:impact] ||= 0.5
    data[:impact] = 1.0 if data[:impact] > 1.0
    data[:impact] = 0.0 if data[:impact] < 0.0
    data[:id] = id

    # if the code field is empty try and pull info from dependencies
    if data[:code].empty? && parent_profile.nil?
      locked_dependencies.dep_list.each do |_name, dep|
        profile = dep.profile
        code = Inspec::MethodSource.code_at(data[:source_location], profile.source_reader)
        data[:code] = code unless code.nil? || code.empty?
        break unless data[:code].empty?
      end
    end
    data
  end.compact

  # resolve hash structure in groups
  res[:groups] = res[:groups].map do |id, group|
    group[:id] = id
    group
  end

  # add information about the required inputs
  if params[:inputs].nil? || params[:inputs].empty?
    # convert to array for backwards compatability
    res[:inputs] = []
  else
    res[:inputs] = params[:inputs].values.map(&:to_hash)
  end
  res[:sha256] = sha256
  res[:parent_profile] = parent_profile unless parent_profile.nil?

  if @supports_platform
    res[:status_message] = @status_message || ""
    res[:status] = failed? ? "failed" : "loaded"
  else
    res[:status] = "skipped"
    msg = "Skipping profile: '#{name}' on unsupported platform: '#{backend.platform.name}/#{backend.platform.release}'."
    res[:status_message] = msg
  end

  # convert legacy os-* supports to their platform counterpart
  if res[:supports] && !res[:supports].empty?
    res[:supports].each do |support|
      # TODO: deprecate
      support[:"platform-family"] = support.delete(:"os-family") if support.key?(:"os-family")
      support[:"platform-name"] = support.delete(:"os-name") if support.key?(:"os-name")
    end
  end

  res
end

#info!Object

return info using uncached params



515
516
517
# File 'lib/inspec/profile.rb', line 515

def info!
  info(load_params.dup)
end

#info_from_parse(include_tests: false) ⇒ Object

Return data like profile.info(params), but try to do so without evaluating the profile.



581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/inspec/profile.rb', line 581

def info_from_parse(include_tests: false)
  return @info_from_parse unless @info_from_parse.nil?

  @info_from_parse = {
    controls: [],
    groups: [],
  }

  # TODO - look at the various source contents
  # PASS 1: parse them using rubocop-ast
  #   Look for controls, top-level metadata, and inputs
  # PASS 2: Using the control IDs, deterimine the extents -
  # line locations - of the coontrol IDs in each file, and
  # then extract each source code block. Use this to populate the source code
  # locations and 'code' properties.

  # TODO: Verify that it doesn't do evaluation (ideally shouldn't because it is reading simply yaml file)
  @info_from_parse = @info_from_parse.merge(.params)

  inputs_hash = {}
  # Note: This only handles the case when inputs are defined in metadata file
  if @profile_id.nil?
    # identifying inputs using profile name
    inputs_hash = Inspec::InputRegistry.list_inputs_for_profile(@info_from_parse[:name])
  else
    inputs_hash = Inspec::InputRegistry.list_inputs_for_profile(@profile_id)
  end

  # TODO: Verify if I need to do the below conversion for inputs to array
  if inputs_hash.nil? || inputs_hash.empty?
    # convert to array for backwards compatability
    @info_from_parse[:inputs] = []
  else
    @info_from_parse[:inputs] = inputs_hash.values.map(&:to_hash)
  end

  @info_from_parse[:sha256] = sha256

  # Populate :status and :status_message
  if supports_platform?
    @info_from_parse[:status_message] = @status_message || ""
    @info_from_parse[:status] = failed? ? "failed" : "loaded"
  else
    @info_from_parse[:status] = "skipped"
    msg = "Skipping profile: '#{name}' on unsupported platform: '#{backend.platform.name}/#{backend.platform.release}'."
    @info_from_parse[:status_message] = msg
  end

  # @source_reader.tests contains a hash mapping control filenames to control file contents
  @source_reader.tests.each do |control_filename, control_file_source|
    # Parse the source code
    src = RuboCop::AST::ProcessedSource.new(control_file_source, RUBY_VERSION.to_f)
    source_location_ref = @source_reader.target.abs_path(control_filename)

    input_collector = Inspec::Profile::AstHelper::InputCollectorOutsideControlBlock.new(@info_from_parse)
    ctl_id_collector = Inspec::Profile::AstHelper::ControlIDCollector.new(@info_from_parse, source_location_ref,
                                                                          include_tests: include_tests)

    # Collect all metadata defined in the control block and inputs defined inside the control block
    src.ast&.each_node { |n|
      ctl_id_collector.process(n)
      input_collector.process(n)
    }

    # For each control ID
    #  Look for per-control metadata
    # Filter controls by --controls, list of controls to include is available in include_controls_list

    # NOTE: This is a hack to duplicate refs.
    # TODO: Fix this in the ref collector or the way we traverse the AST
    @info_from_parse[:controls].each { |control| control[:refs].uniq! }

    @info_from_parse[:controls] = filter_controls_by_id_and_tags(@info_from_parse[:controls])

    # Update groups after filtering controls to handle --controls option
    update_groups_from(control_filename, src)

    # NOTE: This is a hack to duplicate inputs.
    # TODO: Fix this in the input collector or the way we traverse the AST
    @info_from_parse[:inputs] = @info_from_parse[:inputs].uniq
  end
  @info_from_parse
end

#install_gem_dependency(gem_data) ⇒ Object

Requires gem_data as argument. gem_dta example: { name: “gem_name”, version: “0.0.1”}



503
504
505
506
507
508
# File 'lib/inspec/profile.rb', line 503

def install_gem_dependency(gem_data)
  gem_dependency = DependencyInstaller.new(nil, [gem_data])
  gem_dependency.install
rescue Inspec::GemDependencyInstallError => e
  raise e.message
end

#legacy_checkObject

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength



748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
# File 'lib/inspec/profile.rb', line 748

def legacy_check # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength
  # initial values for response object
  result = {
    summary: {
      valid: false,
      timestamp: Time.now.iso8601,
      location: @target,
      profile: nil,
      controls: 0,
    },
    errors: [],
    warnings: [],
    offenses: [],
  }

  entry = lambda { |file, line, column, control, msg|
    {
      file: file,
      line: line,
      column: column,
      control_id: control,
      msg: msg,
    }
  }

  warn = lambda { |file, line, column, control, msg|
    @logger.warn(msg)
    result[:warnings].push(entry.call(file, line, column, control, msg))
  }

  error = lambda { |file, line, column, control, msg|
    @logger.error(msg)
    result[:errors].push(entry.call(file, line, column, control, msg))
  }

  offense = lambda { |file, line, column, control, msg|
    result[:offenses].push(entry.call(file, line, column, control, msg))
  }

  @logger.info "Checking profile in #{@target}"
  meta_path = @source_reader.target.abs_path(@source_reader..ref)

  # verify metadata
  m_errors, m_warnings = .valid
  m_errors.each { |msg| error.call(meta_path, 0, 0, nil, msg) }
  m_warnings.each { |msg| warn.call(meta_path, 0, 0, nil, msg) }
  m_unsupported = .unsupported
  m_unsupported.each { |u| warn.call(meta_path, 0, 0, nil, "doesn't support: #{u}") }
  @logger.info "Metadata OK." if m_errors.empty? && m_unsupported.empty?

  # only run the vendor check if the legacy profile-path is not used as argument
  if @legacy_profile_path == false
    # verify that a lockfile is present if we have dependencies
    unless .dependencies.empty?
      error.call(meta_path, 0, 0, nil, "Your profile needs to be vendored with `inspec vendor`.") unless lockfile_exists?
    end

    if lockfile_exists?
      # verify if metadata and lockfile are out of sync
      if lockfile.deps.size != .dependencies.size
        error.call(meta_path, 0, 0, nil, "inspec.yml and inspec.lock are out-of-sync. Please re-vendor with `inspec vendor`.")
      end

      # verify if metadata and lockfile have the same dependency names
      .dependencies.each do |dep|
        # Skip if the dependency does not specify a name
        next if dep[:name].nil?

        # TODO: should we also verify that the soure is the same?
        unless lockfile.deps.map { |x| x[:name] }.include? dep[:name]
          error.call(meta_path, 0, 0, nil, "Cannot find #{dep[:name]} in lockfile. Please re-vendor with `inspec vendor`.")
        end
      end
    end
  end

  # extract profile name
  result[:summary][:profile] = .params[:name]

  count = params[:controls].values.length
  result[:summary][:controls] = count
  if count == 0
    warn.call(nil, nil, nil, nil, "No controls or tests were defined.")
  else
    @logger.info("Found #{count} controls.")
  end

  # iterate over hash of groups
  params[:controls].each do |id, control|
    sfile = control[:source_location][:ref]
    sline = control[:source_location][:line]
    error.call(sfile, sline, nil, id, "Avoid controls with empty IDs") if id.nil? || id.empty?
    next if id.start_with? "(generated "

    warn.call(sfile, sline, nil, id, "Control #{id} has no title") if control[:title].to_s.empty?
    warn.call(sfile, sline, nil, id, "Control #{id} has no descriptions") if control[:descriptions][:default].to_s.empty?
    warn.call(sfile, sline, nil, id, "Control #{id} has impact > 1.0") if control[:impact].to_f > 1.0
    warn.call(sfile, sline, nil, id, "Control #{id} has impact < 0.0") if control[:impact].to_f < 0.0
    warn.call(sfile, sline, nil, id, "Control #{id} has no tests defined") if control[:checks].nil? || control[:checks].empty?
  end

  # Running cookstyle to check for code offenses
  if @check_cookstyle
    cookstyle_linting_check.each do |lint_output|
      data = lint_output.split(":")
      msg = "#{data[-2]}:#{data[-1]}"
      offense.call(data[0], data[1], data[2], nil, msg)
    end
  end
  # profile is valid if we could not find any error & offenses
  result[:summary][:valid] = result[:errors].empty? && result[:offenses].empty?

  @logger.info "Control definitions OK." if result[:warnings].empty?
  result
end

#load_dependenciesObject



1172
1173
1174
1175
1176
1177
1178
1179
1180
# File 'lib/inspec/profile.rb', line 1172

def load_dependencies
  config = {
    cwd: cwd,
    cache: @cache,
    backend: @backend,
    parent_profile: name,
  }
  Inspec::DependencySet.from_lockfile(lockfile, config, { inputs: @input_values })
end

#load_gem_dependenciesObject

Loads the required gems specified in the Profile’s metadata file from default inspec gems path i.e. ~/.inspec/gems else installs and loads them.



464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/inspec/profile.rb', line 464

def load_gem_dependencies
  gem_dependencies = collect_gem_dependencies
  gem_dependencies.each do |gem_data|

    dependency_loader = DependencyLoader.new
    if dependency_loader.gem_version_installed?(gem_data[:name], gem_data[:version]) ||
        dependency_loader.gem_installed?(gem_data[:name])
      load_gem_dependency(gem_data)
    else
      if Inspec::Config.cached[:auto_install_gems]
        install_gem_dependency(gem_data)
        load_gem_dependency(gem_data)
      else
        ui = Inspec::UI.new
        gem_dependencies.each { |gem_dependency| ui.list_item("#{gem_dependency[:name]} #{gem_dependency[:version]}") }
        choice = ui.prompt.select("The above listed gem dependencies are required to run the profile. Would you like to install them ?", %w{Yes No})
        if choice == "Yes"
          Inspec::Config.cached[:auto_install_gems] = true
          load_gem_dependencies
        else
          ui.error "Unable to resolve above listed profile gem dependencies."
          Inspec::UI.new.exit(:gem_dependency_load_error)
        end
      end
    end
  end
end

#load_gem_dependency(gem_data) ⇒ Object

Requires gem_data as argument. gem_dta example: { name: “gem_name”, version: “0.0.1”}



494
495
496
497
498
499
# File 'lib/inspec/profile.rb', line 494

def load_gem_dependency(gem_data)
  dependency_loader = DependencyLoader.new(nil, [gem_data])
  dependency_loader.load
rescue Inspec::GemDependencyLoadError => e
  raise e.message
end

#load_librariesObject



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/inspec/profile.rb', line 413

def load_libraries
  return @runner_context if @libraries_loaded

  locked_dependencies.dep_list.each_with_index do |(_name, dep), index|
    d = dep.profile
    # this will force a dependent profile load so we are only going to add
    # this metadata if the parent profile is supported.
    if @supports_platform && !d.supports_platform?
      # since ruby 1.9 hashes are ordered so we can just use index values here
      # TODO: NO! this is a violation of encapsulation to an extreme
      if .dependencies[index]
        .dependencies[index][:status] = "skipped"
        msg = "Skipping profile: '#{d.name}' on unsupported platform: '#{d.backend.platform.name}/#{d.backend.platform.release}'."
        .dependencies[index][:status_message] = msg
        .dependencies[index][:skip_message] = msg # Repeat as skip_message for backward compatibility
      end
      next
    elsif .dependencies[index]
      # Currently wrapper profiles will load all dependencies, and then we
      # load them again when we dive down. This needs to be re-done.
      .dependencies[index][:status] = "loaded"
    end

    # rubocop:disable Layout/ExtraSpacing
    c = d.load_libraries                           # !!!RECURSE!!!
    @runner_context.add_resources(c)
  end

  # TODO: why?!? we own both sides of this code
  libs = libraries.map(&:reverse)

  @runner_context.load_libraries(libs)
  @libraries_loaded = true
  @runner_context
end

#locked_dependenciesObject



1114
1115
1116
# File 'lib/inspec/profile.rb', line 1114

def locked_dependencies
  @locked_dependencies ||= load_dependencies
end

#lockfileObject



1151
1152
1153
1154
1155
1156
1157
# File 'lib/inspec/profile.rb', line 1151

def lockfile
  @lockfile ||= if lockfile_exists?
                  Inspec::Lockfile.from_content(@source_reader.target.read("inspec.lock"))
                else
                  generate_lockfile
                end
end

#lockfile_exists?Boolean

Returns:

  • (Boolean)


1118
1119
1120
# File 'lib/inspec/profile.rb', line 1118

def lockfile_exists?
  @source_reader.target.files.include?("inspec.lock")
end

#lockfile_pathObject



1122
1123
1124
# File 'lib/inspec/profile.rb', line 1122

def lockfile_path
  File.join(cwd, "inspec.lock")
end

#metadata_srcObject



1138
1139
1140
# File 'lib/inspec/profile.rb', line 1138

def 
  @source_reader.
end

#nameObject



171
172
173
# File 'lib/inspec/profile.rb', line 171

def name
  .params[:name]
end

#paramsObject



237
238
239
# File 'lib/inspec/profile.rb', line 237

def params
  @params ||= load_params
end

#readmeObject



1134
1135
1136
# File 'lib/inspec/profile.rb', line 1134

def readme
  @source_reader.readme&.values&.first
end

#root_pathObject



1126
1127
1128
# File 'lib/inspec/profile.rb', line 1126

def root_path
  @source_reader.target.prefix
end

#set_status_message(msg) ⇒ Object



1058
1059
1060
# File 'lib/inspec/profile.rb', line 1058

def set_status_message(msg)
  @status_message = msg.to_s
end

#sha256Type

Calculate this profile’s SHA256 checksum. Includes metadata, dependencies, libraries, data files, and controls.

Returns:

  • (Type)

    description of returned object



1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
# File 'lib/inspec/profile.rb', line 1186

def sha256
  # get all dependency checksums
  deps = Hash[locked_dependencies.list.map { |k, v| [k, v.profile.sha256] }]

  res = OpenSSL::Digest.new("SHA256")
  files = source_reader.tests.to_a + source_reader.libraries.to_a +
    source_reader.data_files.to_a +
    [["inspec.yml", source_reader..content]] +
    [["inspec.lock.deps", YAML.dump(deps)]]

  files.sort_by { |a| a[0] }
    .map { |f| res << f[0] << "\0" << f[1] << "\0" }

  res.digest.unpack("H*")[0]
end

#signed?Boolean

Returns:

  • (Boolean)


196
197
198
199
# File 'lib/inspec/profile.rb', line 196

def signed?
  # Signed profiles have .iaf extension
  (@source_reader&.target&.parent&.class == Inspec::IafProvider)
end

#supported?Boolean

Is this profile is supported on the current platform of the backend machine and the current inspec version.

Returns:

  • (Boolean)


213
214
215
# File 'lib/inspec/profile.rb', line 213

def supported?
  supports_platform? && supports_runtime?
end

#supports_platform?Boolean

We need to check if we’re using a Mock’d backend for tests to function.

Returns:

  • (Boolean)


219
220
221
222
223
224
225
226
227
228
# File 'lib/inspec/profile.rb', line 219

def supports_platform?
  if @supports_platform.nil?
    @supports_platform = .supports_platform?(@backend)
  end
  if @backend.backend.class.to_s == "Train::Transports::Mock::Connection"
    @supports_platform = true
  end

  @supports_platform
end

#supports_runtime?Boolean

Returns:

  • (Boolean)


230
231
232
233
234
235
# File 'lib/inspec/profile.rb', line 230

def supports_runtime?
  if @supports_runtime.nil?
    @supports_runtime = .supports_runtime?
  end
  @supports_runtime
end

#to_sObject



510
511
512
# File 'lib/inspec/profile.rb', line 510

def to_s
  "Inspec::Profile<#{name}>"
end

#update_groups_from(control_filename, src) ⇒ Object



695
696
697
698
699
700
701
702
703
704
705
706
707
# File 'lib/inspec/profile.rb', line 695

def update_groups_from(control_filename, src)
  group_data = {
    id: control_filename,
    title: nil,
  }
  source_location_ref = @source_reader.target.abs_path(control_filename)
  Inspec::Profile::AstHelper::TitleCollector.new(group_data)
    .process(src.ast&.child_nodes&.first) # Picking the title defined for the whole controls file
  group_controls = @info_from_parse[:controls].select { |control| control[:source_location][:ref] == source_location_ref }
  group_data[:controls] = group_controls.map { |control| control[:id] }

  @info_from_parse[:groups].push(group_data) if include_group_data?(group_data)
end

#validity_checkObject

rubocop:disable Metrics/AbcSize



988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
# File 'lib/inspec/profile.rb', line 988

def validity_check # rubocop:disable Metrics/AbcSize
  errors = []
  warnings = []
  info_from_parse.merge!(.params)

  %w{name version}.each do |field|
    next unless info_from_parse[field.to_sym].nil?

    errors.push("Missing profile #{field} in #{metadata.ref}")
  end

  if %r{[\/\\]} =~ info_from_parse[:name]
    errors.push("The profile name (#{info_from_parse[:name]}) contains a slash" \
                  " which is not permitted. Please remove all slashes from `inspec.yml`.")
  end

  # if version is set, ensure it is correct
  if !info_from_parse[:version].nil? && !.valid_version?(info_from_parse[:version])
    errors.push("Version needs to be in SemVer format")
  end

  if info_from_parse[:entitlement_id] && info_from_parse[:entitlement_id].strip.empty?
    errors.push("Entitlement ID should not be blank.")
  end

  unless .supports_runtime?
    warnings.push("The current inspec version #{Inspec::VERSION} cannot satisfy profile inspec_version constraint #{info_from_parse[:inspec_version]}")
  end

  %w{title summary maintainer copyright license}.each do |field|
    next unless info_from_parse[field.to_sym].nil?

    warnings.push("Missing profile #{field} in #{metadata.ref}")
  end

  # if license is set, ensure it is in SPDX format or marked as proprietary
  if !info_from_parse[:license].nil? && !.valid_license?(info_from_parse[:license])
    warnings.push("License '#{info_from_parse[:license]}' needs to be in SPDX format or marked as 'Proprietary'. See https://spdx.org/licenses/.")
  end

  # If gem_dependencies is set, it must be an array of hashes with keys name and optional version
  unless info_from_parse[:gem_dependencies].nil?
    list = info_from_parse[:gem_dependencies]
    if list.is_a?(Array) && list.all? { |e| e.is_a? Hash }
      list.each do |entry|
        errors.push("gem_dependencies entries must all have a 'name' field") unless entry.key?(:name)
        if entry[:version]
          orig = entry[:version]
          begin
            # Split on commas as we may have a complex dep
            orig.split(",").map { |c| Gem::Requirement.parse(c) }
          rescue Gem::Requirement::BadRequirementError
            errors.push "Unparseable gem dependency '#{orig}' for #{entry[:name]}"
          rescue Inspec::GemDependencyInstallError => e
            errors.push e.message
          end
        end
        extra = (entry.keys - i{name version})
        unless extra.empty?
          warnings.push "Unknown gem_dependencies key(s) #{extra.join(",")} seen for entry '#{entry[:name]}'"
        end
      end
    else
      errors.push("gem_dependencies must be a List of Hashes")
    end
  end

  [errors, warnings]
end

#verify_if_signedObject



187
188
189
190
191
192
193
194
# File 'lib/inspec/profile.rb', line 187

def verify_if_signed
  if signed?
    verify_signed_profile
    true
  else
    false
  end
end

#verify_signed_profileObject



201
202
203
204
205
# File 'lib/inspec/profile.rb', line 201

def verify_signed_profile
  # Kitchen inspec send target profile in Hash format in some scenarios. For example: While using local profile with kitchen, {:path => "path/to/kitchen/lcoal-profile"}
  target_profile = target.is_a?(Hash) ? target.values[0] : target
  InspecPlugins::Sign::Base.profile_verify(target_profile, true) if target_profile
end

#versionObject



175
176
177
# File 'lib/inspec/profile.rb', line 175

def version
  .params[:version]
end

#virtual_profile?Boolean

Returns:

  • (Boolean)


241
242
243
244
245
# File 'lib/inspec/profile.rb', line 241

def virtual_profile?
  # A virtual profile is for virtual profile evaluation
  # Used by shell & inspec detect command.
  (name == "inspec-shell") && (files&.length == 1) && (files[0] == "inspec.yml")
end

#writable?Boolean

Returns:

  • (Boolean)


179
180
181
# File 'lib/inspec/profile.rb', line 179

def writable?
  @writable
end