Class: InspecPlugins::Compliance::CLI

Inherits:
Object
  • Object
show all
Includes:
Inspec::Dist
Defined in:
lib/plugins/inspec-compliance/lib/inspec-compliance/cli.rb

Constant Summary

Constants included from Inspec::Dist

Inspec::Dist::AUTOMATE_PRODUCT_NAME, Inspec::Dist::COMPLIANCE_PRODUCT_NAME, Inspec::Dist::EXEC_NAME, Inspec::Dist::PRODUCT_NAME, Inspec::Dist::SERVER_PRODUCT_NAME

Instance Method Summary collapse

Instance Method Details

#download(profile_name) ⇒ Object



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
# File 'lib/plugins/inspec-compliance/lib/inspec-compliance/cli.rb', line 105

def download(profile_name)
  Inspec.with_feature("inspec-cli-compliance-download") {
    o = options.dup
    configure_logger(o)

    config = InspecPlugins::Compliance::Configuration.new
    return unless loggedin(config)

    profile_name = InspecPlugins::Compliance::API.sanitize_profile_name(profile_name)
    if InspecPlugins::Compliance::API.exist?(config, profile_name)
      puts "Downloading `#{profile_name}`"

      fetcher = InspecPlugins::Compliance::Fetcher.resolve(
        {
          compliance: profile_name,
        }
      )

      # we provide a name, the fetcher adds the extension
      _owner, id = profile_name.split("/")
      file_name = fetcher.fetch(o.name || id)
      puts "Profile stored to #{file_name}"
    else
      puts "Profile #{profile_name} is not available in #{AUTOMATE_PRODUCT_NAME}."
      exit 1
    end
  }
end

#exec(*tests) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/plugins/inspec-compliance/lib/inspec-compliance/cli.rb', line 78

def exec(*tests)
  Inspec.with_feature("inspec-cli-compliance-exec") {
    begin
      compliance_config = InspecPlugins::Compliance::Configuration.new
      return unless loggedin(compliance_config)

      o = config # o is an Inspec::Config object, provided by a helper method from Inspec::BaseCLI
      diagnose(o)
      configure_logger(o)

      # iterate over tests and add compliance scheme
      tests = tests.map { |t| "compliance://" + InspecPlugins::Compliance::API.sanitize_profile_name(t) }

      runner = Inspec::Runner.new(o)
      tests.each { |target| runner.add_target(target) }

      exit runner.run
    rescue ArgumentError, RuntimeError, Train::UserError => e
      $stderr.puts e.message
      exit 1
    end
  }
end

#login(server) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/plugins/inspec-compliance/lib/inspec-compliance/cli.rb', line 35

def (server)
  Inspec.with_feature("inspec-cli-compliance-login") {
    options["server"] = server
     = InspecPlugins::Compliance::API.(options)
    puts 
  }
end

#logoutObject



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/plugins/inspec-compliance/lib/inspec-compliance/cli.rb', line 255

def logout
  Inspec.with_feature("inspec-cli-compliance-logout") {
    config = InspecPlugins::Compliance::Configuration.new
    unless config.supported?(:oidc) || config["token"].nil? || config["server_type"] == "automate"
      config = InspecPlugins::Compliance::Configuration.new
      url = "#{config["server"]}/logout"
      InspecPlugins::Compliance::HTTP.post(url, config["token"], config["insecure"], !config.supported?(:oidc))
    end
    success = config.destroy

    if success
      puts "Successfully logged out"
    else
      puts "Could not log out"
    end
  }
end

#profilesObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/plugins/inspec-compliance/lib/inspec-compliance/cli.rb', line 46

def profiles
  Inspec.with_feature("inspec-cli-compliance-profiles") {
    begin
      config = InspecPlugins::Compliance::Configuration.new
      return unless loggedin(config)

      # set owner to config
      config["owner"] = options["owner"] || config["user"]

      msg, profiles = InspecPlugins::Compliance::API.profiles(config)
      profiles.sort_by! { |hsh| hsh["title"] }
      if !profiles.empty?
        # iterate over profiles
        headline("Available profiles:")
        profiles.each do |profile|
          owner = profile["owner_id"] || profile["owner"]
          li("#{profile["title"]} v#{profile["version"]} (#{mark_text(owner + "/" + profile["name"])})")
        end
      else
        puts msg if msg != "success"
        puts "Could not find any profiles"
        exit 1
      end
    rescue InspecPlugins::Compliance::ServerConfigurationMissing
      $stderr.puts "\nServer configuration information is missing. Please login using `#{EXEC_NAME} #{subcommand_name} login`"
      exit 1
    end
  }
end

#upload(path) ⇒ Object

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



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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/plugins/inspec-compliance/lib/inspec-compliance/cli.rb', line 139

def upload(path) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
  Inspec.with_feature("inspec-cli-compliance-upload") {
    config = InspecPlugins::Compliance::Configuration.new
    return unless loggedin(config)

    # set owner to config
    config["owner"] = options["owner"] || config["user"]

    unless File.exist?(path)
      puts "Directory #{path} does not exist."
      exit 1
    end

    vendor_deps(path, options) if File.directory?(path)

    o = options.dup
    configure_logger(o)

    # only run against the mock backend, otherwise we run against the local system
    o[:backend] = Inspec::Backend.create(Inspec::Config.mock)
    o[:check_mode] = true
    o[:vendor_cache] = Inspec::Cache.new(o[:vendor_cache])

    # check the profile, we only allow to upload valid profiles
    profile = Inspec::Profile.for_target(path, o)

    # start verification process
    error_count = 0
    error = lambda { |msg|
      error_count += 1
      puts msg
    }

    result = profile.check
    unless result[:summary][:valid]
      error.call("Profile check failed. Please fix the profile before upload.")
    else
      puts("Profile is valid")
    end

    # determine user information
    if (config["token"].nil? && config["refresh_token"].nil?) || config["user"].nil?
      error.call("Please login via `#{EXEC_NAME} #{subcommand_name} login`")
    end

    # read profile name from inspec.yml
    profile_name = profile.name

    # read profile version from inspec.yml
    profile_version = profile.version

    # check that the profile is not uploaded already,
    # confirm upload to the user (overwrite with --force)
    if InspecPlugins::Compliance::API.exist?(config, "#{config["owner"]}/#{profile_name}##{profile_version}") && !options["overwrite"]
      error.call("Profile exists on the server, use --overwrite")
    end

    # abort if we found an error
    if error_count > 0
      puts "Found #{error_count} error(s)"
      exit 1
    end

    # if it is a directory, tar it to tmp directory
    generated = false
    if File.directory?(path)
      generated = true
      archive_path = Dir::Tmpname.create([profile_name, ".tar.gz"]) {}
      puts "Generate temporary profile archive at #{archive_path}"
      profile.archive({ output: archive_path, ignore_errors: false, overwrite: true })
    else
      archive_path = path
    end

    puts "Start upload to #{config["owner"]}/#{profile_name}"
    pname = ERB::Util.url_encode(profile_name)

    puts "Uploading to #{AUTOMATE_PRODUCT_NAME}"

    success, msg = InspecPlugins::Compliance::API.upload(config, config["owner"], pname, archive_path)

    # delete temp file if it was temporary generated
    File.delete(archive_path) if generated && File.exist?(archive_path)

    if success
      puts "Successfully uploaded profile"
    else
      puts "Error during profile upload:"
      puts msg
      exit 1
    end
  }
end

#versionObject



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/plugins/inspec-compliance/lib/inspec-compliance/cli.rb', line 234

def version
  Inspec.with_feature("inspec-cli-compliance-version") {
    begin
      config = InspecPlugins::Compliance::Configuration.new
      info = InspecPlugins::Compliance::API.version(config)
      if !info.nil? && info["build_timestamp"]
        # key info["api"] is not longer available in latest version api response
        puts "Name: automate"
        puts "Version: #{info["build_timestamp"]}"
      else
        puts "Could not determine server version."
        exit 1
      end
    rescue InspecPlugins::Compliance::ServerConfigurationMissing
      puts "\nServer configuration information is missing. Please login using `#{EXEC_NAME} #{subcommand_name} login`"
      exit 1
    end
  }
end