Class: Vault::Client

Inherits:
Object
  • Object
show all
Includes:
Configurable
Defined in:
lib/vault/client.rb,
lib/vault/api/sys.rb,
lib/vault/api/auth.rb,
lib/vault/api/help.rb,
lib/vault/api/logical.rb,
lib/vault/api/auth_token.rb

Constant Summary collapse

USER_AGENT =

The user agent for this client.

"VaultRuby/#{Vault::VERSION} (+github.com/hashicorp/vault-ruby)".freeze
DEFAULT_HEADERS =

The default headers that are sent with every request.

{
  "Content-Type" => "application/json",
  "Accept"       => "application/json",
  "User-Agent"   => USER_AGENT,
}.freeze
JSON_PARSE_OPTIONS =

The default list of options to use when parsing JSON.

{
  max_nesting:      false,
  create_additions: false,
  symbolize_names:  true,
}.freeze
RESCUED_EXCEPTIONS =
[].tap do |a|
  # Failure to even open the socket (usually permissions)
  a << SocketError

  # Failed to reach the server (aka bad URL)
  a << Errno::ECONNREFUSED

  # Failed to read body or no response body given
  a << EOFError

  # Timeout (Ruby 1.9-)
  a << Timeout::Error

  # Timeout (Ruby 1.9+) - Ruby 1.9 does not define these constants so we
  # only add them if they are defiend
  a << Net::ReadTimeout if defined?(Net::ReadTimeout)
  a << Net::OpenTimeout if defined?(Net::OpenTimeout)
end.freeze

Instance Method Summary collapse

Methods included from Configurable

#configure, keys, #options

Constructor Details

#initialize(options = {}) ⇒ Vault::Client

Create a new Client with the given options. Any options given take precedence over the default options.



56
57
58
59
60
61
62
# File 'lib/vault/client.rb', line 56

def initialize(options = {})
  # Use any options given, but fall back to the defaults set on the module
  Vault::Configurable.keys.each do |key|
    value = options.key?(key) ? options[key] : Defaults.public_send(key)
    instance_variable_set(:"@#{key}", value)
  end
end

Instance Method Details

#authAuth

A proxy to the Auth methods.

Returns:



10
11
12
# File 'lib/vault/api/auth.rb', line 10

def auth
  @auth ||= Authenticate.new(self)
end

#auth_tokenAuthToken

A proxy to the AuthToken methods.

Returns:



12
13
14
# File 'lib/vault/api/auth_token.rb', line 12

def auth_token
  @auth_token ||= AuthToken.new(self)
end

#build_uri(verb, path, params = {}) ⇒ URI

Construct a URL from the given verb and path. If the request is a GET or DELETE request, the params are assumed to be query params are are converted as such using #to_query_string.

If the path is relative, it is merged with the Defaults.address attribute. If the path is absolute, it is converted to a URI object and returned.

Parameters:

  • verb (Symbol)

    the lowercase HTTP verb (e.g. :get)

  • path (String)

    the absolute or relative HTTP path (url) to get

  • params (Hash) (defaults to: {})

    the list of params to build the URI with (for GET and DELETE requests)

Returns:

  • (URI)


251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/vault/client.rb', line 251

def build_uri(verb, path, params = {})
  # Add any query string parameters
  if [:delete, :get].include?(verb)
    path = [path, to_query_string(params)].compact.join("?")
  end

  # Parse the URI
  uri = URI.parse(path)

  # Don't merge absolute URLs
  uri = URI.parse(File.join(address, path)) unless uri.absolute?

  # Return the URI object
  uri
end

#class_for_request(verb) ⇒ Class

Helper method to get the corresponding Net::HTTP class from the given HTTP verb.

Parameters:

  • verb (#to_s)

    the HTTP verb to create a class from

Returns:

  • (Class)


274
275
276
# File 'lib/vault/client.rb', line 274

def class_for_request(verb)
  Net::HTTP.const_get(verb.to_s.capitalize)
end

#delete(path, params = {}, headers = {}) ⇒ Object

Perform a DELETE request.

See Also:



96
97
98
# File 'lib/vault/client.rb', line 96

def delete(path, params = {}, headers = {})
  request(:delete, path, params, headers)
end

#error(response) ⇒ Object

Raise a response error, extracting as much information from the server’s response as possible.

Parameters:

  • response (HTTP::Message)

    the response object from the request

Raises:



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/vault/client.rb', line 316

def error(response)
  if response.body && response.body.match("missing client token")
    raise MissingTokenError
  end

  if (response.content_type || '').include?("json")
    # Attempt to parse the error as JSON
    begin
      json = JSON.parse(response.body, JSON_PARSE_OPTIONS)

      if json[:errors]
        raise HTTPError.new(address, response.code, json[:errors])
      end
    rescue JSON::ParserError; end
  end

  raise HTTPError.new(address, response.code, [response.body])
end

#get(path, params = {}, headers = {}) ⇒ Object

Perform a GET request.

See Also:



72
73
74
# File 'lib/vault/client.rb', line 72

def get(path, params = {}, headers = {})
  request(:get, path, params, headers)
end

#help(path) ⇒ Help

Gets help for the given path.

Examples:

Vault.help #=> #<Vault::Help help="..." see_also="...">

Parameters:

  • path (String)

    the path to get help for

Returns:



18
19
20
21
# File 'lib/vault/api/help.rb', line 18

def help(path)
  json = self.get("/v1/#{path}", help: 1)
  return Help.decode(json)
end

#logicalLogical

A proxy to the Logical methods.

Returns:



10
11
12
# File 'lib/vault/api/logical.rb', line 10

def logical
  @logical ||= Logical.new(self)
end

#patch(path, data, headers = {}) ⇒ Object

Perform a PATCH request.

See Also:



90
91
92
# File 'lib/vault/client.rb', line 90

def patch(path, data, headers = {})
  request(:patch, path, data, headers)
end

#post(path, data, headers = {}) ⇒ Object

Perform a POST request.

See Also:



78
79
80
# File 'lib/vault/client.rb', line 78

def post(path, data, headers = {})
  request(:post, path, data, headers)
end

#put(path, data, headers = {}) ⇒ Object

Perform a PUT request.

See Also:



84
85
86
# File 'lib/vault/client.rb', line 84

def put(path, data, headers = {})
  request(:put, path, data, headers)
end

#request(verb, path, data = {}, headers = {}) ⇒ String, Hash

Make an HTTP request with the given verb, data, params, and headers. If the response has a return type of JSON, the JSON is automatically parsed and returned as a hash; otherwise it is returned as a string.

Parameters:

  • verb (Symbol)

    the lowercase symbol of the HTTP verb (e.g. :get, :delete)

  • path (String)

    the absolute or relative path from Defaults.address to make the request against

  • data (#read, Hash, nil) (defaults to: {})

    the data to use (varies based on the verb)

  • headers (Hash) (defaults to: {})

    the list of headers to use

Returns:

  • (String, Hash)

    the response body

Raises:

  • (HTTPError)

    if the request is not an HTTP 200 OK



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
232
233
# File 'lib/vault/client.rb', line 119

def request(verb, path, data = {}, headers = {})
  # Build the URI and request object from the given information
  uri = build_uri(verb, path, data)
  request = class_for_request(verb).new(uri.request_uri)

  # Add headers
  headers = DEFAULT_HEADERS.merge(headers)
  headers.each do |key, value|
    request.add_field(key, value)
  end

  # Setup PATCH/POST/PUT
  if [:patch, :post, :put].include?(verb)
    if data.respond_to?(:read)
      request.content_length = data.size
      request.body_stream = data
    elsif data.is_a?(Hash)
      request.form_data = data
    else
      request.body = data
    end
  end

  # Create the HTTP connection object - since the proxy information defaults
  # to +nil+, we can just pass it to the initializer method instead of doing
  # crazy strange conditionals.
  connection = Net::HTTP.new(uri.host, uri.port,
    proxy_address, proxy_port, proxy_username, proxy_password)

  # Use a custom open timeout
  if open_timeout || timeout
    connection.open_timeout = (open_timeout || timeout).to_i
  end

  # Use a custom read timeout
  if read_timeout || timeout
    connection.read_timeout = (read_timeout || timeout).to_i
  end

  # Create the cookie for the request.
  cookie = CGI::Cookie.new
  cookie.name    = "token"
  cookie.value   = token
  cookie.path    = "/"
  cookie.expires = Time.now + (60*60*24*365)

  # Apply SSL, if applicable
  if uri.scheme == "https"
    # Turn on SSL
    connection.use_ssl = true

    # Vault requires TLS1.2
    connection.ssl_version = "TLSv1_2"

    # Only use secure ciphers
    connection.ciphers = ssl_ciphers

    # Turn on secure cookies
    cookie.secure = true

    # Custom pem files, no problem!
    if ssl_pem_file
      pem = File.read(ssl_pem_file)
      connection.cert = OpenSSL::X509::Certificate.new(pem)
      connection.key = OpenSSL::PKey::RSA.new(pem, ssl_pem_passphrase)
      connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
    end

    # Use custom CA cert for verification
    if ssl_ca_cert
      connection.ca_file = ssl_ca_cert
    end

    # Use custom CA path that contains CA certs
    if ssl_ca_path
      connection.ca_path = ssl_ca_path
    end

    # Naughty, naughty, naughty! Don't blame me when someone hops in
    # and executes a MITM attack!
    if !ssl_verify
      connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end

    # Use custom timeout for connecting and verifying via SSL
    if ssl_timeout || timeout
      connection.ssl_timeout = (ssl_timeout || timeout).to_i
    end
  end

  # Add the cookie to the request if a token was given.
  if !token.nil?
    request["Cookie"] = cookie.to_s
  end

  begin
    # Create a connection using the block form, which will ensure the socket
    # is properly closed in the event of an error.
    connection.start do |http|
      response = http.request(request)

      case response
      when Net::HTTPRedirection
        redirect = URI.parse(response["location"])
        request(verb, redirect, data, headers)
      when Net::HTTPSuccess
        success(response)
      else
        error(response)
      end
    end
  rescue *RESCUED_EXCEPTIONS => e
    raise HTTPConnectionError.new(address, e)
  end
end

#same_options?(opts) ⇒ true, false

Determine if the given options are the same as ours.

Returns:

  • (true, false)


66
67
68
# File 'lib/vault/client.rb', line 66

def same_options?(opts)
  options.hash == opts.hash
end

#success(response) ⇒ String, Hash

Parse the response object and manipulate the result based on the given Content-Type header. For now, this method only parses JSON, but it could be expanded in the future to accept other content types.

Parameters:

  • response (HTTP::Message)

    the response object from the request

Returns:

  • (String, Hash)

    the parsed response, as an object



301
302
303
304
305
306
307
# File 'lib/vault/client.rb', line 301

def success(response)
  if response.body && (response.content_type || '').include?("json")
    JSON.parse(response.body, JSON_PARSE_OPTIONS)
  else
    response.body
  end
end

#sysSys

A proxy to the Sys methods.

Returns:



9
10
11
# File 'lib/vault/api/sys.rb', line 9

def sys
  @sys ||= Sys.new(self)
end

#to_query_string(hash) ⇒ String?

Convert the given hash to a list of query string parameters. Each key and value in the hash is URI-escaped for safety.

Parameters:

  • hash (Hash)

    the hash to create the query string from

Returns:

  • (String, nil)

    the query string as a string, or nil if there are no params



286
287
288
289
290
# File 'lib/vault/client.rb', line 286

def to_query_string(hash)
  hash.map do |key, value|
    "#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}"
  end.join('&')[/.+/]
end