Class: Compliance::HTTP
- Inherits:
-
Object
- Object
- Compliance::HTTP
- Defined in:
- lib/bundles/inspec-compliance/http.rb
Overview
implements a simple http abstraction on top of Net::HTTP
Class Method Summary collapse
-
.get(url, headers = nil, insecure) ⇒ Object
generic get requires.
-
.post(url, token, insecure, basic_auth = false) ⇒ Object
generic post request.
-
.post_file(url, headers, file_path, insecure) ⇒ Object
post a file.
-
.send_request(uri, req, insecure) ⇒ Object
sends a http requests.
Class Method Details
.get(url, headers = nil, insecure) ⇒ Object
generic get requires
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/bundles/inspec-compliance/http.rb', line 12 def self.get(url, headers = nil, insecure) url = "https://#{url}" if URI.parse(url).scheme.nil? uri = URI.parse(url) req = Net::HTTP::Get.new(uri.path) if !headers.nil? headers.each do |key, value| req.add_field(key, value) end end send_request(uri, req, insecure) end |
.post(url, token, insecure, basic_auth = false) ⇒ Object
generic post request
25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/bundles/inspec-compliance/http.rb', line 25 def self.post(url, token, insecure, basic_auth = false) # form request uri = URI.parse(url) req = Net::HTTP::Post.new(uri.path) if basic_auth req.basic_auth token, '' else req['Authorization'] = "Bearer #{token}" end req.form_data={} send_request(uri, req, insecure) end |
.post_file(url, headers, file_path, insecure) ⇒ Object
post a file
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/bundles/inspec-compliance/http.rb', line 40 def self.post_file(url, headers, file_path, insecure) uri = URI.parse(url) raise "Unable to parse URL: #{url}" if uri.nil? || uri.host.nil? http = Net::HTTP.new(uri.host, uri.port) # set connection flags http.use_ssl = (uri.scheme == 'https') http.verify_mode = OpenSSL::SSL::VERIFY_NONE if insecure req = Net::HTTP::Post.new(uri.path) headers.each do |key, value| req.add_field(key, value) end req.body_stream=File.open(file_path, 'rb') req.add_field('Content-Length', File.size(file_path)) req.add_field('Content-Type', 'application/x-gtar') boundary = 'INSPEC-PROFILE-UPLOAD' req.add_field('session', boundary) res=http.request(req) res end |
.send_request(uri, req, insecure) ⇒ Object
sends a http requests
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/bundles/inspec-compliance/http.rb', line 65 def self.send_request(uri, req, insecure) opts = { use_ssl: uri.scheme == 'https', } opts[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if insecure raise "Unable to parse URI: #{uri}" if uri.nil? || uri.host.nil? res = Net::HTTP.start(uri.host, uri.port, opts) { |http| http.request(req) } res rescue OpenSSL::SSL::SSLError => e raise e unless e..include? 'certificate verify failed' puts "Error: Failed to connect to #{uri}." puts 'If the server uses a self-signed certificate, please re-run the login command with the --insecure option.' exit 1 end |