summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/http_spec.rb
blob: 57e4b4fc74bc7fd97f7913390591ef9ba3014c97 (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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::HTTP do
  include StubRequests

  let(:default_options) { described_class::DEFAULT_TIMEOUT_OPTIONS }

  context 'when allow_local_requests' do
    it 'sends the request to the correct URI' do
      stub_full_request('https://example.org:8080', ip_address: '8.8.8.8').to_return(status: 200)

      described_class.get('https://example.org:8080', allow_local_requests: false)

      expect(WebMock).to have_requested(:get, 'https://8.8.8.8:8080').once
    end
  end

  context 'when not allow_local_requests' do
    it 'sends the request to the correct URI' do
      stub_full_request('https://example.org:8080')

      described_class.get('https://example.org:8080', allow_local_requests: true)

      expect(WebMock).to have_requested(:get, 'https://8.8.8.9:8080').once
    end
  end

  context 'when reading the response is too slow' do
    before(:all) do
      # Override Net::HTTP to add a delay between sending each response chunk
      mocked_http = Class.new(Net::HTTP) do
        def request(*)
          super do |response|
            response.instance_eval do
              def read_body(*)
                @body.each do |fragment|
                  sleep 0.002.seconds

                  yield fragment if block_given?
                end
              end
            end

            yield response if block_given?

            response
          end
        end
      end

      @original_net_http = Net.send(:remove_const, :HTTP)
      @webmock_net_http = WebMock::HttpLibAdapters::NetHttpAdapter.instance_variable_get(:@webMockNetHTTP)

      Net.send(:const_set, :HTTP, mocked_http)
      WebMock::HttpLibAdapters::NetHttpAdapter.instance_variable_set(:@webMockNetHTTP, mocked_http)

      # Reload Gitlab::NetHttpAdapter
      Gitlab.send(:remove_const, :NetHttpAdapter)
      load "#{Rails.root}/lib/gitlab/net_http_adapter.rb"
    end

    before do
      stub_const("#{described_class}::DEFAULT_READ_TOTAL_TIMEOUT", 0.001.seconds)

      WebMock.stub_request(:post, /.*/).to_return do |request|
        { body: %w(a b), status: 200 }
      end
    end

    after(:all) do
      Net.send(:remove_const, :HTTP)
      Net.send(:const_set, :HTTP, @original_net_http)
      WebMock::HttpLibAdapters::NetHttpAdapter.instance_variable_set(:@webMockNetHTTP, @webmock_net_http)

      # Reload Gitlab::NetHttpAdapter
      Gitlab.send(:remove_const, :NetHttpAdapter)
      load "#{Rails.root}/lib/gitlab/net_http_adapter.rb"
    end

    let(:options) { {} }

    subject(:request_slow_responder) { described_class.post('http://example.org', **options) }

    it 'raises an error' do
      expect { request_slow_responder }.to raise_error(Gitlab::HTTP::ReadTotalTimeout, /Request timed out after ?([0-9]*[.])?[0-9]+ seconds/)
    end

    context 'and timeout option is greater than DEFAULT_READ_TOTAL_TIMEOUT' do
      let(:options) { { timeout: 10.seconds } }

      it 'does not raise an error' do
        expect { request_slow_responder }.not_to raise_error
      end
    end

    context 'and stream_body option is truthy' do
      let(:options) { { stream_body: true } }

      it 'does not raise an error' do
        expect { request_slow_responder }.not_to raise_error
      end
    end
  end

  it 'calls a block' do
    WebMock.stub_request(:post, /.*/)

    expect { |b| described_class.post('http://example.org', &b) }.to yield_with_args
  end

  describe 'allow_local_requests_from_web_hooks_and_services is' do
    before do
      WebMock.stub_request(:get, /.*/).to_return(status: 200, body: 'Success')
    end

    context 'disabled' do
      before do
        allow(Gitlab::CurrentSettings).to receive(:allow_local_requests_from_web_hooks_and_services?).and_return(false)
      end

      it 'deny requests to localhost' do
        expect { described_class.get('http://localhost:3003') }.to raise_error(Gitlab::HTTP::BlockedUrlError)
      end

      it 'deny requests to private network' do
        expect { described_class.get('http://192.168.1.2:3003') }.to raise_error(Gitlab::HTTP::BlockedUrlError)
      end

      context 'if allow_local_requests set to true' do
        it 'override the global value and allow requests to localhost or private network' do
          stub_full_request('http://localhost:3003')

          expect { described_class.get('http://localhost:3003', allow_local_requests: true) }.not_to raise_error
        end
      end
    end

    context 'enabled' do
      before do
        allow(Gitlab::CurrentSettings).to receive(:allow_local_requests_from_web_hooks_and_services?).and_return(true)
      end

      it 'allow requests to localhost' do
        stub_full_request('http://localhost:3003')

        expect { described_class.get('http://localhost:3003') }.not_to raise_error
      end

      it 'allow requests to private network' do
        expect { described_class.get('http://192.168.1.2:3003') }.not_to raise_error
      end

      context 'if allow_local_requests set to false' do
        it 'override the global value and ban requests to localhost or private network' do
          expect { described_class.get('http://localhost:3003', allow_local_requests: false) }.to raise_error(Gitlab::HTTP::BlockedUrlError)
        end
      end
    end
  end

  describe 'handle redirect loops' do
    before do
      stub_full_request("http://example.org", method: :any).to_raise(HTTParty::RedirectionTooDeep.new("Redirection Too Deep"))
    end

    it 'handles GET requests' do
      expect { described_class.get('http://example.org') }.to raise_error(Gitlab::HTTP::RedirectionTooDeep)
    end

    it 'handles POST requests' do
      expect { described_class.post('http://example.org') }.to raise_error(Gitlab::HTTP::RedirectionTooDeep)
    end

    it 'handles PUT requests' do
      expect { described_class.put('http://example.org') }.to raise_error(Gitlab::HTTP::RedirectionTooDeep)
    end

    it 'handles DELETE requests' do
      expect { described_class.delete('http://example.org') }.to raise_error(Gitlab::HTTP::RedirectionTooDeep)
    end

    it 'handles HEAD requests' do
      expect { described_class.head('http://example.org') }.to raise_error(Gitlab::HTTP::RedirectionTooDeep)
    end
  end

  describe 'setting default timeouts' do
    before do
      stub_full_request('http://example.org', method: :any)
    end

    context 'when no timeouts are set' do
      it 'sets default open and read and write timeouts' do
        expect(described_class).to receive(:httparty_perform_request).with(
          Net::HTTP::Get, 'http://example.org', default_options
        ).and_call_original

        described_class.get('http://example.org')
      end
    end

    context 'when :timeout is set' do
      it 'does not set any default timeouts' do
        expect(described_class).to receive(:httparty_perform_request).with(
          Net::HTTP::Get, 'http://example.org', { timeout: 1 }
        ).and_call_original

        described_class.get('http://example.org', { timeout: 1 })
      end
    end

    context 'when :open_timeout is set' do
      it 'only sets default read and write timeout' do
        expect(described_class).to receive(:httparty_perform_request).with(
          Net::HTTP::Get, 'http://example.org', default_options.merge(open_timeout: 1)
        ).and_call_original

        described_class.get('http://example.org', open_timeout: 1)
      end
    end

    context 'when :read_timeout is set' do
      it 'only sets default open and write timeout' do
        expect(described_class).to receive(:httparty_perform_request).with(
          Net::HTTP::Get, 'http://example.org', default_options.merge(read_timeout: 1)
        ).and_call_original

        described_class.get('http://example.org', read_timeout: 1)
      end
    end

    context 'when :write_timeout is set' do
      it 'only sets default open and read timeout' do
        expect(described_class).to receive(:httparty_perform_request).with(
          Net::HTTP::Put, 'http://example.org', default_options.merge(write_timeout: 1)
        ).and_call_original

        described_class.put('http://example.org', write_timeout: 1)
      end
    end
  end

  describe '.try_get' do
    let(:path) { 'http://example.org' }

    let(:extra_log_info_proc) do
      proc do |error, url, options|
        { klass: error.class, url: url, options: options }
      end
    end

    let(:request_options) do
      default_options.merge({
        verify: false,
        basic_auth: { username: 'user', password: 'pass' }
      })
    end

    described_class::HTTP_ERRORS.each do |exception_class|
      context "with #{exception_class}" do
        let(:klass) { exception_class }

        context 'with path' do
          before do
            expect(described_class).to receive(:httparty_perform_request)
              .with(Net::HTTP::Get, path, default_options)
              .and_raise(klass)
          end

          it 'handles requests without extra_log_info' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), {})

            expect(described_class.try_get(path)).to be_nil
          end

          it 'handles requests with extra_log_info as hash' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), { a: :b })

            expect(described_class.try_get(path, extra_log_info: { a: :b })).to be_nil
          end

          it 'handles requests with extra_log_info as proc' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), { url: path, klass: klass, options: {} })

            expect(described_class.try_get(path, extra_log_info: extra_log_info_proc)).to be_nil
          end
        end

        context 'with path and options' do
          before do
            expect(described_class).to receive(:httparty_perform_request)
              .with(Net::HTTP::Get, path, request_options)
              .and_raise(klass)
          end

          it 'handles requests without extra_log_info' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), {})

            expect(described_class.try_get(path, request_options)).to be_nil
          end

          it 'handles requests with extra_log_info as hash' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), { a: :b })

            expect(described_class.try_get(path, **request_options, extra_log_info: { a: :b })).to be_nil
          end

          it 'handles requests with extra_log_info as proc' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), { klass: klass, url: path, options: request_options })

            expect(described_class.try_get(path, **request_options, extra_log_info: extra_log_info_proc)).to be_nil
          end
        end

        context 'with path, options, and block' do
          let(:block) do
            proc {}
          end

          before do
            expect(described_class).to receive(:httparty_perform_request)
              .with(Net::HTTP::Get, path, request_options, &block)
              .and_raise(klass)
          end

          it 'handles requests without extra_log_info' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), {})

            expect(described_class.try_get(path, request_options, &block)).to be_nil
          end

          it 'handles requests with extra_log_info as hash' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), { a: :b })

            expect(described_class.try_get(path, **request_options, extra_log_info: { a: :b }, &block)).to be_nil
          end

          it 'handles requests with extra_log_info as proc' do
            expect(Gitlab::ErrorTracking)
              .to receive(:log_exception)
              .with(instance_of(klass), { klass: klass, url: path, options: request_options })

            expect(described_class.try_get(path, **request_options, extra_log_info: extra_log_info_proc, &block)).to be_nil
          end
        end
      end
    end
  end
end