Class: ChefHandlerForeman::ForemanUploader

Inherits:
Object
  • Object
show all
Defined in:
lib/chef_handler_foreman/foreman_uploader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ ForemanUploader

Returns a new instance of ForemanUploader.



25
26
27
# File 'lib/chef_handler_foreman/foreman_uploader.rb', line 25

def initialize(opts)
  @options = opts
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



23
24
25
# File 'lib/chef_handler_foreman/foreman_uploader.rb', line 23

def options
  @options
end

Instance Method Details

#foreman_request(path, body, client_name) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/chef_handler_foreman/foreman_uploader.rb', line 29

def foreman_request(path, body, client_name)
  uri              = URI.parse(options[:url])
  http             = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl     = uri.scheme == 'https'
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  if http.use_ssl?
    if options[:foreman_ssl_ca] && !options[:foreman_ssl_ca].empty?
      http.ca_file     = options[:foreman_ssl_ca]
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    end

    if options[:foreman_ssl_cert] && !options[:foreman_ssl_cert].empty? && options[:foreman_ssl_key] && !options[:foreman_ssl_key].empty?
      http.cert = OpenSSL::X509::Certificate.new(File.read(options[:foreman_ssl_cert]))
      http.key  = OpenSSL::PKey::RSA.new(File.read(options[:foreman_ssl_key]), nil)
    end
  end

  req = Net::HTTP::Post.new("#{uri.path}/#{path}")
  req.add_field('Accept', 'application/json,version=2')
  req.content_type = 'application/json'
  body_json        = body.to_json
  req.body         = body_json
  req.add_field('X-Foreman-Signature', sign_request(body_json, options[:client_key]))
  req.add_field('X-Foreman-Client', client_name)
  response         = http.request(req)
end

#sign_request(body_json, key_path) ⇒ Object



57
58
59
60
61
62
# File 'lib/chef_handler_foreman/foreman_uploader.rb', line 57

def sign_request(body_json, key_path)
  hash_body = Digest::SHA256.hexdigest(body_json)
  key = OpenSSL::PKey::RSA.new(File.read(key_path))
  # Base64.encode64 is adding \n in the string
  signature = Base64.encode64(key.sign(OpenSSL::Digest::SHA256.new, hash_body)).gsub("\n",'')
end