summaryrefslogtreecommitdiff
path: root/spec/unit/network/http/connection_spec.rb
blob: ef6ca65d6ce37c153ccbf280468ef764469016dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
234
235
236
237
238
239
240
241
242
243
244
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
#! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/network/http/connection'
require 'puppet/network/authentication'

describe Puppet::Network::HTTP::Connection do

  let (:host) { "me" }
  let (:port) { 54321 }
  subject { Puppet::Network::HTTP::Connection.new(host, port, :verify => Puppet::SSL::Validator.no_validator) }
  let (:httpok) { Net::HTTPOK.new('1.1', 200, '') }

  context "when providing HTTP connections" do
    context "when initializing http instances" do
      it "should return an http instance created with the passed host and port" do
        conn = Puppet::Network::HTTP::Connection.new(host, port, :verify => Puppet::SSL::Validator.no_validator)

        expect(conn.address).to eq(host)
        expect(conn.port).to eq(port)
      end

      it "should enable ssl on the http instance by default" do
        conn = Puppet::Network::HTTP::Connection.new(host, port, :verify => Puppet::SSL::Validator.no_validator)

        expect(conn).to be_use_ssl
      end

      it "can disable ssl using an option" do
        conn = Puppet::Network::HTTP::Connection.new(host, port, :use_ssl => false, :verify => Puppet::SSL::Validator.no_validator)

        expect(conn).to_not be_use_ssl
      end

      it "can enable ssl using an option" do
        conn = Puppet::Network::HTTP::Connection.new(host, port, :use_ssl => true, :verify => Puppet::SSL::Validator.no_validator)

        expect(conn).to be_use_ssl
      end

      it "should raise Puppet::Error when invalid options are specified" do
        expect { Puppet::Network::HTTP::Connection.new(host, port, :invalid_option => nil) }.to raise_error(Puppet::Error, 'Unrecognized option(s): :invalid_option')
      end
    end
  end

  context "when methods that accept a block are called with a block" do
    let (:host) { "my_server" }
    let (:port) { 8140 }
    let (:subject) { Puppet::Network::HTTP::Connection.new(host, port, :use_ssl => false, :verify => Puppet::SSL::Validator.no_validator) }

    before :each do
      httpok.stubs(:body).returns ""

      # This stubbing relies a bit more on knowledge of the internals of Net::HTTP
      # than I would prefer, but it works on ruby 1.8.7 and 1.9.3, and it seems
      # valuable enough to have tests for blocks that this is probably warranted.
      socket = stub_everything("socket")
      TCPSocket.stubs(:open).returns(socket)

      Net::HTTP::Post.any_instance.stubs(:exec).returns("")
      Net::HTTP::Head.any_instance.stubs(:exec).returns("")
      Net::HTTP::Get.any_instance.stubs(:exec).returns("")
      Net::HTTPResponse.stubs(:read_new).returns(httpok)
    end

    [:request_get, :request_head, :request_post].each do |method|
      context "##{method}" do
        it "should yield to the block" do
          block_executed = false
          subject.send(method, "/foo", {}) do |response|
            block_executed = true
          end
          block_executed.should == true
        end
      end
    end
  end

  class ConstantErrorValidator
    def initialize(args)
      @fails_with = args[:fails_with]
      @error_string = args[:error_string] || ""
      @peer_certs = args[:peer_certs] || []
    end

    def setup_connection(connection)
      connection.stubs(:start).raises(OpenSSL::SSL::SSLError.new(@fails_with))
    end

    def peer_certs
      @peer_certs
    end

    def verify_errors
      [@error_string]
    end
  end

  class NoProblemsValidator
    def initialize(cert)
      @cert = cert
    end

    def setup_connection(connection)
    end

    def peer_certs
      [@cert]
    end

    def verify_errors
      []
    end
  end

  shared_examples_for 'ssl verifier' do
    include PuppetSpec::Files

    let (:host) { "my_server" }
    let (:port) { 8140 }

    it "should provide a useful error message when one is available and certificate validation fails", :unless => Puppet.features.microsoft_windows? do
      connection = Puppet::Network::HTTP::Connection.new(
        host, port,
        :verify => ConstantErrorValidator.new(:fails_with => 'certificate verify failed',
                                              :error_string => 'shady looking signature'))

      expect do
        connection.get('request')
      end.to raise_error(Puppet::Error, "certificate verify failed: [shady looking signature]")
    end

    it "should provide a helpful error message when hostname was not match with server certificate", :unless => Puppet.features.microsoft_windows? do
      Puppet[:confdir] = tmpdir('conf')

      connection = Puppet::Network::HTTP::Connection.new(
      host, port,
      :verify => ConstantErrorValidator.new(
        :fails_with => 'hostname was not match with server certificate',
        :peer_certs => [Puppet::SSL::CertificateAuthority.new.generate(
          'not_my_server', :dns_alt_names => 'foo,bar,baz')]))

      expect do
        connection.get('request')
      end.to raise_error(Puppet::Error) do |error|
        error.message =~ /Server hostname 'my_server' did not match server certificate; expected one of (.+)/
        $1.split(', ').should =~ %w[DNS:foo DNS:bar DNS:baz DNS:not_my_server not_my_server]
      end
    end

    it "should pass along the error message otherwise" do
      connection = Puppet::Network::HTTP::Connection.new(
        host, port,
        :verify => ConstantErrorValidator.new(:fails_with => 'some other message'))

      expect do
        connection.get('request')
      end.to raise_error(/some other message/)
    end

    it "should check all peer certificates for upcoming expiration", :unless => Puppet.features.microsoft_windows? do
      Puppet[:confdir] = tmpdir('conf')
      cert = Puppet::SSL::CertificateAuthority.new.generate(
        'server', :dns_alt_names => 'foo,bar,baz')

      connection = Puppet::Network::HTTP::Connection.new(
        host, port,
        :verify => NoProblemsValidator.new(cert))

      Net::HTTP.any_instance.stubs(:start)
      Net::HTTP.any_instance.stubs(:request).returns(httpok)

      connection.expects(:warn_if_near_expiration).with(cert)

      connection.get('request')
    end
  end

  context "when using single use HTTPS connections" do
    it_behaves_like 'ssl verifier' do
    end
  end

  context "when using persistent HTTPS connections" do
    around :each do |example|
      pool = Puppet::Network::HTTP::Pool.new
      Puppet.override(:http_pool => pool) do
        example.run
      end
      pool.close
    end

    it_behaves_like 'ssl verifier' do
    end
  end

  context "when response is a redirect" do
    let (:site)       { Puppet::Network::HTTP::Site.new('http', 'my_server', 8140) }
    let (:other_site) { Puppet::Network::HTTP::Site.new('http', 'redirected', 9292) }
    let (:other_path) { "other-path" }
    let (:verify) { Puppet::SSL::Validator.no_validator }
    let (:subject) { Puppet::Network::HTTP::Connection.new(site.host, site.port, :use_ssl => false, :verify => verify) }
    let (:httpredirection) do
      response = Net::HTTPFound.new('1.1', 302, 'Moved Temporarily')
      response['location'] = "#{other_site.addr}/#{other_path}"
      response.stubs(:read_body).returns("This resource has moved")
      response
    end

    def create_connection(site, options)
      options[:use_ssl] = site.use_ssl?
      Puppet::Network::HTTP::Connection.new(site.host, site.port, options)
    end

    it "should redirect to the final resource location" do
      http = stub('http')
      http.stubs(:request).returns(httpredirection).then.returns(httpok)

      seq = sequence('redirection')
      pool = Puppet.lookup(:http_pool)
      pool.expects(:with_connection).with(site, anything).yields(http).in_sequence(seq)
      pool.expects(:with_connection).with(other_site, anything).yields(http).in_sequence(seq)

      conn = create_connection(site, :verify => verify)
      conn.get('/foo')
    end

    def expects_redirection(conn, &block)
      http = stub('http')
      http.stubs(:request).returns(httpredirection)

      pool = Puppet.lookup(:http_pool)
      pool.expects(:with_connection).with(site, anything).yields(http)
      pool
    end

    def expects_limit_exceeded(conn)
      expect {
        conn.get('/')
      }.to raise_error(Puppet::Network::HTTP::RedirectionLimitExceededException)
    end

    it "should not redirect when the limit is 0" do
      conn = create_connection(site, :verify => verify, :redirect_limit => 0)

      pool = expects_redirection(conn)
      pool.expects(:with_connection).with(other_site, anything).never

      expects_limit_exceeded(conn)
    end

    it "should redirect only once" do
      conn = create_connection(site, :verify => verify, :redirect_limit => 1)

      pool = expects_redirection(conn)
      pool.expects(:with_connection).with(other_site, anything).once

      expects_limit_exceeded(conn)
    end

    it "should raise an exception when the redirect limit is exceeded" do
      conn = create_connection(site, :verify => verify, :redirect_limit => 3)

      pool = expects_redirection(conn)
      pool.expects(:with_connection).with(other_site, anything).times(3)

      expects_limit_exceeded(conn)
    end
  end

  it "allows setting basic auth on get requests" do
    expect_request_with_basic_auth

    subject.get('/path', nil, :basic_auth => { :user => 'user', :password => 'password' })
  end

  it "allows setting basic auth on post requests" do
    expect_request_with_basic_auth

    subject.post('/path', 'data', nil, :basic_auth => { :user => 'user', :password => 'password' })
  end

  it "allows setting basic auth on head requests" do
    expect_request_with_basic_auth

    subject.head('/path', nil, :basic_auth => { :user => 'user', :password => 'password' })
  end

  it "allows setting basic auth on delete requests" do
    expect_request_with_basic_auth

    subject.delete('/path', nil, :basic_auth => { :user => 'user', :password => 'password' })
  end

  it "allows setting basic auth on put requests" do
    expect_request_with_basic_auth

    subject.put('/path', 'data', nil, :basic_auth => { :user => 'user', :password => 'password' })
  end

  def expect_request_with_basic_auth
    Net::HTTP.any_instance.expects(:request).with do |request|
      expect(request['authorization']).to match(/^Basic/)
    end.returns(httpok)
  end
end