2017-01-05 19:29:11 +00:00
|
|
|
# encoding: utf-8
|
|
|
|
# copyright: 2017, Criteo
|
2017-02-02 21:13:03 +00:00
|
|
|
# copyright: 2017, Chef Software Inc
|
|
|
|
# author: Guilhem Lettron, Christoph Hartmann
|
2017-01-05 19:29:11 +00:00
|
|
|
# license: Apache v2
|
|
|
|
|
2017-02-02 21:13:03 +00:00
|
|
|
require 'faraday'
|
2017-01-26 13:18:49 +00:00
|
|
|
require 'hashie'
|
2017-01-05 19:29:11 +00:00
|
|
|
|
|
|
|
module Inspec::Resources
|
|
|
|
class Http < Inspec.resource(1)
|
|
|
|
name 'http'
|
|
|
|
desc 'Use the http InSpec audit resource to test http call.'
|
|
|
|
example "
|
|
|
|
describe http('http://localhost:8080/ping', auth: {user: 'user', pass: 'test'}, params: {format: 'html'}) do
|
|
|
|
its('status') { should cmp 200 }
|
|
|
|
its('body') { should cmp 'pong' }
|
2017-01-26 13:18:49 +00:00
|
|
|
its('headers.Content-Type') { should cmp 'text/html' }
|
|
|
|
end
|
|
|
|
|
|
|
|
describe http('http://example.com/ping').headers do
|
|
|
|
its('Content-Length') { should cmp 258 }
|
|
|
|
its('Content-Type') { should cmp 'text/html; charset=UTF-8' }
|
2017-01-05 19:29:11 +00:00
|
|
|
end
|
|
|
|
"
|
|
|
|
|
2017-05-19 15:23:11 +00:00
|
|
|
def initialize(url, opts = {})
|
2017-01-05 19:29:11 +00:00
|
|
|
@url = url
|
2017-05-19 15:23:11 +00:00
|
|
|
@method = opts.fetch(:method, 'GET')
|
|
|
|
@params = opts.fetch(:params, nil)
|
|
|
|
@auth = opts.fetch(:auth, {})
|
|
|
|
@headers = opts.fetch(:headers, {})
|
|
|
|
@data = opts.fetch(:data, nil)
|
|
|
|
@open_timeout = opts.fetch(:open_timeout, 60)
|
|
|
|
@read_timeout = opts.fetch(:read_timeout, 60)
|
|
|
|
@ssl_verify = opts.fetch(:ssl_verify, true)
|
2017-01-05 19:29:11 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def status
|
|
|
|
response.status
|
|
|
|
end
|
|
|
|
|
|
|
|
def body
|
2017-02-02 21:13:03 +00:00
|
|
|
response.body
|
2017-01-05 19:29:11 +00:00
|
|
|
end
|
|
|
|
|
2017-01-26 13:18:49 +00:00
|
|
|
def headers
|
|
|
|
Hashie::Mash.new(response.headers.to_h)
|
2017-01-05 19:29:11 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def to_s
|
2017-01-26 13:18:49 +00:00
|
|
|
"http #{@method} on #{@url}"
|
2017-01-05 19:29:11 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def response
|
2017-04-14 18:52:01 +00:00
|
|
|
conn = Faraday.new url: @url, headers: @headers, params: @params, ssl: { verify: @ssl_verify }
|
2017-02-02 21:13:03 +00:00
|
|
|
|
|
|
|
# set basic authentication
|
|
|
|
conn.basic_auth @auth[:user], @auth[:pass] unless @auth.empty?
|
|
|
|
|
|
|
|
# set default timeout
|
2017-05-19 15:23:11 +00:00
|
|
|
conn.options.timeout = @read_timeout # open/read timeout in seconds
|
|
|
|
conn.options.open_timeout = @open_timeout # connection open timeout in seconds
|
2017-02-02 21:13:03 +00:00
|
|
|
|
|
|
|
@response = conn.send(@method.downcase) do |req|
|
|
|
|
req.body = @data
|
|
|
|
end
|
2017-01-05 19:29:11 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|