Class: Vault::Client
- Inherits:
-
Object
- Object
- Vault::Client
- Includes:
- Configurable
- Defined in:
- lib/vault/api/kv.rb,
lib/vault/client.rb,
lib/vault/api/sys.rb,
lib/vault/api/auth.rb,
lib/vault/api/help.rb,
lib/vault/api/approle.rb,
lib/vault/api/logical.rb,
lib/vault/api/auth_tls.rb,
lib/vault/api/transform.rb,
lib/vault/api/auth_token.rb
Constant Summary collapse
- USER_AGENT =
The user agent for this client.
"VaultRuby/#{Vault::VERSION} (+github.com/khiav223577/vault_ruby_client)".freeze
- TOKEN_HEADER =
The name of the header used to hold the Vault token.
"X-Vault-Token".freeze
- NAMESPACE_HEADER =
The name of the header used to hold the Namespace.
"X-Vault-Namespace".freeze
- WRAP_TTL_HEADER =
The name of the header used to hold the wrapped request ttl.
"X-Vault-Wrap-TTL".freeze
- LOCATION_HEADER =
The name of the header used for redirection.
"location".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 a << Errno::EADDRNOTAVAIL # 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) a << PersistentHTTP::Error end.freeze
- MIN_TLS_VERSION =
Vault requires at least TLS1.2
if defined? OpenSSL::SSL::TLS1_2_VERSION OpenSSL::SSL::TLS1_2_VERSION else "TLSv1_2" end
Instance Method Summary collapse
-
#approle ⇒ AppRole
A proxy to the AppRole methods.
-
#auth ⇒ Auth
A proxy to the Auth methods.
-
#auth_tls ⇒ AuthTLS
A proxy to the AuthTLS methods.
-
#auth_token ⇒ AuthToken
A proxy to the AuthToken methods.
-
#build_uri(verb, path, params = {}) ⇒ URI
Construct a URL from the given verb and path.
-
#class_for_request(verb) ⇒ Class
Helper method to get the corresponding Net::HTTP class from the given HTTP verb.
-
#delete(path, params = {}, headers = {}) ⇒ Object
Perform a DELETE request.
-
#error(response) ⇒ Object
Raise a response error, extracting as much information from the server’s response as possible.
-
#get(path, params = {}, headers = {}) ⇒ Object
Perform a GET request.
-
#help(path) ⇒ Help
Gets help for the given path.
-
#initialize(options = {}) ⇒ Vault::Client
constructor
Create a new Client with the given options.
-
#kv(mount) ⇒ KV
A proxy to the KV methods.
-
#list(path, params = {}, headers = {}) ⇒ Object
Perform a LIST request.
-
#logical ⇒ Logical
A proxy to the Logical methods.
-
#patch(path, data, headers = {}) ⇒ Object
Perform a PATCH request.
-
#post(path, data = {}, headers = {}) ⇒ Object
Perform a POST request.
-
#put(path, data, headers = {}) ⇒ Object
Perform a PUT request.
-
#remove_double_slash(path) ⇒ String
Removes double slashes from a path.
-
#request(verb, path, data = {}, headers = {}) ⇒ String, Hash
Make an HTTP request with the given verb, data, params, and headers.
-
#same_options?(opts) ⇒ true, false
Determine if the given options are the same as ours.
-
#shutdown ⇒ Object
Shutdown any open pool connections.
-
#success(response) ⇒ String, Hash
Parse the response object and manipulate the result based on the given
Content-Type
header. -
#sys ⇒ Sys
A proxy to the Sys methods.
-
#to_query_string(hash) ⇒ String?
Convert the given hash to a list of query string parameters.
-
#transform ⇒ Transform
A proxy to the Transform methods.
-
#with_retries(*rescued, &block) ⇒ Object
Execute the given block with retries and exponential backoff.
-
#with_token(token) {|Vault::Client| ... } ⇒ Object
Creates and yields a new client object with the given token.
Methods included from Configurable
Constructor Details
#initialize(options = {}) ⇒ Vault::Client
Create a new Client with the given options. Any options given take precedence over the default options.
80 81 82 83 84 85 86 87 88 89 |
# File 'lib/vault/client.rb', line 80 def initialize( = {}) # Use any options given, but fall back to the defaults set on the module Vault::Configurable.keys.each do |key| value = .key?(key) ? [key] : Defaults.public_send(key) instance_variable_set(:"@#{key}", value) end @lock = Mutex.new @nhp = nil end |
Instance Method Details
#approle ⇒ AppRole
A proxy to the AppRole methods.
15 16 17 |
# File 'lib/vault/api/approle.rb', line 15 def approle @approle ||= AppRole.new(self) end |
#auth ⇒ Auth
A proxy to the Auth methods.
13 14 15 |
# File 'lib/vault/api/auth.rb', line 13 def auth @auth ||= Authenticate.new(self) end |
#auth_tls ⇒ AuthTLS
A proxy to the AuthTLS methods.
15 16 17 |
# File 'lib/vault/api/auth_tls.rb', line 15 def auth_tls @auth_tls ||= AuthTLS.new(self) end |
#auth_token ⇒ AuthToken
A proxy to the AuthToken methods.
15 16 17 |
# File 'lib/vault/api/auth_token.rb', line 15 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.
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
# File 'lib/vault/client.rb', line 333 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? uri.path = remove_double_slash(uri.path) # 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.
358 359 360 |
# File 'lib/vault/client.rb', line 358 def class_for_request(verb) Net::HTTP.const_get(verb.to_s.capitalize) end |
#delete(path, params = {}, headers = {}) ⇒ Object
Perform a DELETE request.
222 223 224 |
# File 'lib/vault/client.rb', line 222 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.
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
# File 'lib/vault/client.rb', line 400 def error(response) if response.body && response.body.match("missing client token") # Vault 1.10+ no longer returns "missing" client token" so we use HTTPClientError klass = HTTPClientError else # Use the correct exception class case response when Net::HTTPPreconditionFailed raise MissingRequiredStateError.new when Net::HTTPClientError klass = HTTPClientError when Net::HTTPServerError klass = HTTPServerError else klass = HTTPError end 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 klass.new(address, response, json[:errors]) end rescue JSON::ParserError; end end raise klass.new(address, response, [response.body]) end |
#get(path, params = {}, headers = {}) ⇒ Object
Perform a GET request.
191 192 193 |
# File 'lib/vault/client.rb', line 191 def get(path, params = {}, headers = {}) request(:get, path, params, headers) end |
#help(path) ⇒ Help
Gets help for the given path.
31 32 33 34 |
# File 'lib/vault/api/help.rb', line 31 def help(path) json = self.get("/v1/#{EncodePath.encode_path(path)}", help: 1) return Help.decode(json) end |
#kv(mount) ⇒ KV
A proxy to the KV methods.
13 14 15 |
# File 'lib/vault/api/kv.rb', line 13 def kv(mount) KV.new(self, mount) end |
#list(path, params = {}, headers = {}) ⇒ Object
Perform a LIST request.
197 198 199 200 |
# File 'lib/vault/client.rb', line 197 def list(path, params = {}, headers = {}) params = params.merge(list: true) request(:get, path, params, headers) end |
#logical ⇒ Logical
A proxy to the Logical methods.
13 14 15 |
# File 'lib/vault/api/logical.rb', line 13 def logical @logical ||= Logical.new(self) end |
#patch(path, data, headers = {}) ⇒ Object
Perform a PATCH request.
216 217 218 |
# File 'lib/vault/client.rb', line 216 def patch(path, data, headers = {}) request(:patch, path, data, headers) end |
#post(path, data = {}, headers = {}) ⇒ Object
Perform a POST request.
204 205 206 |
# File 'lib/vault/client.rb', line 204 def post(path, data = {}, headers = {}) request(:post, path, data, headers) end |
#put(path, data, headers = {}) ⇒ Object
Perform a PUT request.
210 211 212 |
# File 'lib/vault/client.rb', line 210 def put(path, data, headers = {}) request(:put, path, data, headers) end |
#remove_double_slash(path) ⇒ String
Removes double slashes from a path.
313 314 315 |
# File 'lib/vault/client.rb', line 313 def remove_double_slash(path) path.b.gsub(%r{//+}, '/') 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.
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/vault/client.rb', line 245 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) if uri.userinfo() request.basic_auth uri.user, uri.password end # Get a list of headers headers = DEFAULT_HEADERS.merge(headers) # Add the Vault token header - users could still override this on a # per-request basis if !token.nil? headers[TOKEN_HEADER] ||= token end # Add the Vault Namespace header - users could still override this on a # per-request basis if !namespace.nil? headers[NAMESPACE_HEADER] ||= namespace end # Add 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 begin # Create a connection using the block form, which will ensure the socket # is properly closed in the event of an error. response = pool.request(uri, request) case response when Net::HTTPRedirection # On a redirect of a GET or HEAD request, the URL already contains # the data as query string parameters. if [:head, :get].include?(verb) data = {} end request(verb, response[LOCATION_HEADER], data, headers) when Net::HTTPSuccess success(response) else error(response) 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.
185 186 187 |
# File 'lib/vault/client.rb', line 185 def (opts) .hash == opts.hash end |
#shutdown ⇒ Object
Shutdown any open pool connections. Pool will be recreated upon next request.
166 167 168 169 |
# File 'lib/vault/client.rb', line 166 def shutdown @nhp.shutdown() @nhp = nil 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.
385 386 387 388 389 390 391 |
# File 'lib/vault/client.rb', line 385 def success(response) if response.body && (response.content_type || '').include?("json") JSON.parse(response.body, JSON_PARSE_OPTIONS) else response.body end end |
#sys ⇒ Sys
A proxy to the Sys methods.
12 13 14 |
# File 'lib/vault/api/sys.rb', line 12 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.
370 371 372 373 374 |
# File 'lib/vault/client.rb', line 370 def to_query_string(hash) hash.map do |key, value| "#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}" end.join('&')[/.+/] end |
#transform ⇒ Transform
A proxy to the Transform methods.
11 12 13 |
# File 'lib/vault/api/transform.rb', line 11 def transform @transform ||= Transform.new(self) end |
#with_retries(*rescued, &block) ⇒ Object
Execute the given block with retries and exponential backoff.
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 |
# File 'lib/vault/client.rb', line 436 def with_retries(*rescued, &block) = rescued.last.is_a?(Hash) ? rescued.pop : {} exception = nil retries = 0 rescued = Defaults::RETRIED_EXCEPTIONS if rescued.empty? max_attempts = [:attempts] || Defaults::RETRY_ATTEMPTS backoff_base = [:base] || Defaults::RETRY_BASE backoff_max = [:max_wait] || Defaults::RETRY_MAX_WAIT begin return yield retries, exception rescue *rescued => e exception = e retries += 1 raise if retries > max_attempts # Calculate the exponential backoff combined with an element of # randomness. backoff = [backoff_base * (2 ** (retries - 1)), backoff_max].min backoff = backoff * (0.5 * (1 + Kernel.rand)) # Ensure we are sleeping at least the minimum interval. backoff = [backoff_base, backoff].max # Exponential backoff. Kernel.sleep(backoff) # Now retry retry end end |
#with_token(token) {|Vault::Client| ... } ⇒ Object
Creates and yields a new client object with the given token. This may be used safely in a threadsafe manner because the original client remains unchanged. The value of the block is returned.
176 177 178 179 180 181 |
# File 'lib/vault/client.rb', line 176 def with_token(token) client = self.dup client.token = token return yield client if block_given? return nil end |