Class: Spiffe::Workload::HTTPClient

Inherits:
Object
  • Object
show all
Defined in:
lib/spiffe/workload/http_client.rb

Overview

HTTP client with automatic SPIFFE authentication

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ HTTPClient



14
15
16
17
# File 'lib/spiffe/workload/http_client.rb', line 14

def initialize(client)
  @client = client
  @tls_context = TLSConfig.create_auto_updating_context(client)
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



11
12
13
# File 'lib/spiffe/workload/http_client.rb', line 11

def client
  @client
end

Instance Method Details

#delete(uri, headers: {}) ⇒ Object



62
63
64
# File 'lib/spiffe/workload/http_client.rb', line 62

def delete(uri, headers: {})
  request(uri, method: :delete, headers: headers)
end

#get(uri, headers: {}) ⇒ Object

Convenience methods for common HTTP verbs



50
51
52
# File 'lib/spiffe/workload/http_client.rb', line 50

def get(uri, headers: {})
  request(uri, method: :get, headers: headers)
end

#post(uri, body:, headers: {}) ⇒ Object



54
55
56
# File 'lib/spiffe/workload/http_client.rb', line 54

def post(uri, body:, headers: {})
  request(uri, method: :post, body: body, headers: headers)
end

#put(uri, body:, headers: {}) ⇒ Object



58
59
60
# File 'lib/spiffe/workload/http_client.rb', line 58

def put(uri, body:, headers: {})
  request(uri, method: :put, body: body, headers: headers)
end

#request(uri, method: :get, body: nil, headers: {}) ⇒ Net::HTTPResponse

Make an HTTPS request with SPIFFE mTLS



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/spiffe/workload/http_client.rb', line 25

def request(uri, method: :get, body: nil, headers: {})
  uri = URI.parse(uri) if uri.is_a?(String)
  
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.ssl_context = @tls_context
  
  request_class = case method
                  when :get then Net::HTTP::Get
                  when :post then Net::HTTP::Post
                  when :put then Net::HTTP::Put
                  when :delete then Net::HTTP::Delete
                  when :head then Net::HTTP::Head
                  when :patch then Net::HTTP::Patch
                  else raise ArgumentError, "Unsupported method: #{method}"
                  end
  
  request = request_class.new(uri)
  headers.each { |key, value| request[key] = value }
  request.body = body if body
  
  http.request(request)
end