Class: Inspec::Metadata

Inherits:
Object
  • Object
show all
Defined in:
lib/inspec/metadata.rb

Overview

The Metadata class represents a profile’s metadata. This includes the metadata stored in the profile’s metadata.rb file, as well as inferred metadata like if this profile supports the current runtime and the intended target. This class does NOT represent the runtime state of a profile during execution. See lib/inspec/profile.rb for the runtime representation of a profile.

A Metadata object may be created and finalized with invalid data. This allows the check CLI command to analyse the issues. Use valid? to determine if the metadata is coherent.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ref, logger = nil) ⇒ Metadata

Returns a new instance of Metadata.



26
27
28
29
30
31
32
# File 'lib/inspec/metadata.rb', line 26

def initialize(ref, logger = nil)
  @ref = ref
  @logger = logger || Logger.new(nil)
  @content = ""
  @params = {}
  @missing_methods = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sth, *args) ⇒ Object



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

def method_missing(sth, *args)
  @logger.warn "#{ref} doesn't support: #{sth} #{args}"
  @missing_methods.push(sth)
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



25
26
27
# File 'lib/inspec/metadata.rb', line 25

def content
  @content
end

#paramsObject

Returns the value of attribute params.



25
26
27
# File 'lib/inspec/metadata.rb', line 25

def params
  @params
end

#refObject (readonly)

Returns the value of attribute ref.



24
25
26
# File 'lib/inspec/metadata.rb', line 24

def ref
  @ref
end

Class Method Details

.finalize(metadata, profile_id, options, logger = nil) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/inspec/metadata.rb', line 243

def self.finalize(, profile_id, options, logger = nil)
  return nil if .nil?

  param = .params || {}
  options ||= {}
  param["version"] = param["version"].to_s unless param["version"].nil?
  .params = symbolize_keys(param)
  .params[:supports] = finalize_supports(.params[:supports], logger)
  finalize_name(, profile_id, options[:target])

  
end

.finalize_name(metadata, profile_id, original_target) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/inspec/metadata.rb', line 221

def self.finalize_name(, profile_id, original_target)
  # profile_id always overwrites whatever already exists as the name
  unless profile_id.to_s.empty?
    .params[:name] = profile_id.to_s
    return
  end

  # don't overwrite an existing name
  return unless .params[:name].nil?

  # if there's a title, there is no need to set a name too
  return unless .params[:title].nil?

  # create a new name based on the original target if it exists
  # Crudely slug the target to not contain slashes, to avoid breaking
  # unit tests that look for warning sequences
  return if original_target.to_s.empty?

  .params[:title] = "tests from #{original_target}"
  .params[:name] = .params[:title].gsub(%r{[\/\\]}, ".")
end

.finalize_supports(supports, logger) ⇒ Object



213
214
215
216
217
218
219
# File 'lib/inspec/metadata.rb', line 213

def self.finalize_supports(supports, logger)
  case x = supports
  when Hash   then [finalize_supports_elem(x, logger)]
  when Array  then x.map { |e| finalize_supports_elem(e, logger) }.compact
  when nil    then []
  end
end

.finalize_supports_elem(elem, logger) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/inspec/metadata.rb', line 190

def self.finalize_supports_elem(elem, logger)
  case x = elem
  when Hash
    x[:release] = x[:release].to_s if x[:release]
    x
  when Array
    logger.warn(
      "Failed to read supports entry that is an array. Please use "\
      "the `supports: {os-family: xyz}` syntax."
    )
    nil
  when nil then nil
  else
    Inspec.deprecate(
      :supports_syntax,
      "Do not use deprecated `supports: #{x}` syntax. Instead use:\n"\
        "supports:\n  - os-family: #{x}\n\n"
    )

    { :'os-family' => x } # rubocop:disable Style/HashSyntax
  end
end

.from_file(path, profile_id, logger = nil) ⇒ Object



286
287
288
289
290
291
292
293
294
# File 'lib/inspec/metadata.rb', line 286

def self.from_file(path, profile_id, logger = nil)
  unless File.file?(path)
    logger ||= Logger.new(nil)
    logger.error "Can't find metadata file #{path}"
    return nil
  end

  from_ref(File.basename(path), File.read(path), profile_id, logger)
end

.from_ref(ref, content, profile_id, logger = nil) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/inspec/metadata.rb', line 271

def self.from_ref(ref, content, profile_id, logger = nil)
  # NOTE there doesn't have to exist an actual file, it may come from an
  # archive (i.e., content)
  case File.basename(ref)
  when "inspec.yml"
    from_yaml(ref, content, profile_id, logger)
  when "metadata.rb"
    from_ruby(ref, content, profile_id, logger)
  else
    logger ||= Logger.new(nil)
    logger.error "Don't know how to handle metadata in #{ref}"
    nil
  end
end

.from_ruby(ref, content, profile_id, logger = nil) ⇒ Object



264
265
266
267
268
269
# File 'lib/inspec/metadata.rb', line 264

def self.from_ruby(ref, content, profile_id, logger = nil)
  res = Metadata.new(ref, logger)
  res.instance_eval(content, ref, 1)
  res.content = content
  finalize(res, profile_id, {}, logger)
end

.from_yaml(ref, content, profile_id, logger = nil) ⇒ Object



256
257
258
259
260
261
262
# File 'lib/inspec/metadata.rb', line 256

def self.from_yaml(ref, content, profile_id, logger = nil)
  require "erb" unless defined?(Erb)
  res = Metadata.new(ref, logger)
  res.params = YAML.load(ERB.new(content).result)
  res.content = content
  finalize(res, profile_id, {}, logger)
end

.symbolize_keys(obj) ⇒ Object



179
180
181
182
183
184
185
186
187
188
# File 'lib/inspec/metadata.rb', line 179

def self.symbolize_keys(obj)
  return obj.map { |i| symbolize_keys(i) } if obj.is_a?(Array)
  return obj unless obj.is_a?(Hash)

  obj.each_with_object({}) do |(k, v), h|
    v = symbolize_keys(v) if v.is_a?(Hash)
    v = symbolize_keys(v) if v.is_a?(Array)
    h[k.to_sym] = v
  end
end

Instance Method Details

#dependenciesObject



53
54
55
# File 'lib/inspec/metadata.rb', line 53

def dependencies
  params[:depends] || []
end

#gem_dependenciesObject



57
58
59
# File 'lib/inspec/metadata.rb', line 57

def gem_dependencies
  params[:gem_dependencies] || []
end

#inspec_requirementObject



67
68
69
70
71
# File 'lib/inspec/metadata.rb', line 67

def inspec_requirement
  # using Gem::Requirement here to allow nil values which
  # translate to [">= 0"]
  Gem::Requirement.create(params[:inspec_version])
end

#supports(sth, version = nil) ⇒ Object



61
62
63
64
65
# File 'lib/inspec/metadata.rb', line 61

def supports(sth, version = nil)
  # Ignore supports with metadata.rb. This file is legacy and the way it
  # it handles `supports` deprecated. A deprecation warning will be printed
  # already.
end

#supports_platform?(backend) ⇒ Boolean

Returns:

  • (Boolean)


78
79
80
81
# File 'lib/inspec/metadata.rb', line 78

def supports_platform?(backend)
  require "inspec/resources/platform" # break circularity in load
  backend.platform.supported?(params[:supports])
end

#supports_runtime?Boolean

Returns:

  • (Boolean)


73
74
75
76
# File 'lib/inspec/metadata.rb', line 73

def supports_runtime?
  running = Gem::Version.new(Inspec::VERSION)
  inspec_requirement.satisfied_by?(running)
end

#unsupportedObject



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

def unsupported
  @missing_methods
end

#validObject

return all warn and errors



84
85
86
87
88
89
90
91
92
93
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
# File 'lib/inspec/metadata.rb', line 84

def valid # rubocop:disable Metrics/AbcSize
  errors = []
  warnings = []

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

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

  if %r{[\/\\]} =~ params[:name]
    errors.push("The profile name (#{params[: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 !params[:version].nil? && !valid_version?(params[:version])
    errors.push("Version needs to be in SemVer format")
  end

  if params[:entitlement_id] && params[: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 #{params[:inspec_version]}")
  end

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

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

  # if license is set, ensure it is in SPDX format or marked as proprietary
  if !params[:license].nil? && !valid_license?(params[:license])
    warnings.push("License '#{params[: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 params[:gem_dependencies].nil?
    list = params[: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

#valid?Boolean

returns true or false

Returns:

  • (Boolean)


154
155
156
157
# File 'lib/inspec/metadata.rb', line 154

def valid?
  errors, _warnings = valid
  errors.empty? && unsupported.empty?
end

#valid_license?(value) ⇒ Boolean

Returns:

  • (Boolean)


166
167
168
# File 'lib/inspec/metadata.rb', line 166

def valid_license?(value)
  value =~ /^Proprietary[,;]?\b/ || Spdx.valid_license?(value)
end

#valid_version?(value) ⇒ Boolean

Returns:

  • (Boolean)


159
160
161
162
163
164
# File 'lib/inspec/metadata.rb', line 159

def valid_version?(value)
  Semverse::Version.new(value)
  true
rescue Semverse::InvalidVersionFormat
  false
end