Class: Puppetserver::Ca::Utils::HttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/puppetserver/ca/utils/http_client.rb

Overview

Utilities for doing HTTPS against the CA that wraps Net::HTTP constructs

Defined Under Namespace

Classes: Connection, Result, URL

Constant Summary collapse

DEFAULT_HEADERS =
{
  'User-Agent'   => 'PuppetserverCaCli',
  'Content-Type' => 'application/json',
  'Accept'       => 'application/json'
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(settings, with_client_cert: true) ⇒ HttpClient

Not all connections require a client cert to be present. For example, when querying the status endpoint.



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/puppetserver/ca/utils/http_client.rb', line 22

def initialize(settings, with_client_cert: true)
  @store = make_store(settings[:localcacert],
                      settings[:certificate_revocation],
                      settings[:hostcrl])

  if with_client_cert
    @cert = load_cert(settings[:hostcert])
    @key = load_key(settings[:hostprivkey])
  else
    @cert = nil
    @key = nil
  end
end

Instance Attribute Details

#storeObject (readonly)

Returns the value of attribute store.



18
19
20
# File 'lib/puppetserver/ca/utils/http_client.rb', line 18

def store
  @store
end

Instance Method Details

#load_cert(path) ⇒ Object



36
37
38
39
40
# File 'lib/puppetserver/ca/utils/http_client.rb', line 36

def load_cert(path)
  load_with_errors(path, 'hostcert') do |content|
    OpenSSL::X509::Certificate.new(content)
  end
end

#load_key(path) ⇒ Object



42
43
44
45
46
# File 'lib/puppetserver/ca/utils/http_client.rb', line 42

def load_key(path)
  load_with_errors(path, 'hostprivkey') do |content|
    OpenSSL::PKey.read(content)
  end
end

#with_connection(url, &block) ⇒ Object

Takes an instance URL (defined lower in the file), and creates a connection. The given block is passed our own Connection object. The Connection object should have HTTP verbs defined on it that take a body (and optional overrides). Returns whatever the block given returned.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/puppetserver/ca/utils/http_client.rb', line 52

def with_connection(url, &block)
  request = ->(conn) { block.call(Connection.new(conn, url)) }

  begin
    Net::HTTP.start(url.host, url.port,
                    use_ssl: true, cert_store: @store,
                    cert: @cert, key: @key,
                    &request)
  rescue StandardError => e
    raise ConnectionFailed.create(e,
            "Failed connecting to #{url.full_url}\n" +
            "  Root cause: #{e.message}")
  end
end