summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/request_context_spec.rb
blob: 23e45aff1c59aec65d7dbb6a4576cf085a4df12f (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
require 'spec_helper'

describe Gitlab::RequestContext do
  describe '#client_ip' do
    subject { described_class.client_ip }
    let(:app) { -> (env) {} }
    let(:env) { Hash.new }

    context 'with X-Forwarded-For headers', :request_store do
      let(:load_balancer_ip) { '1.2.3.4' }
      let(:headers) do
        {
          'HTTP_X_FORWARDED_FOR' => "#{load_balancer_ip}, 127.0.0.1",
          'REMOTE_ADDR' => '127.0.0.1'
        }
      end

      let(:env) { Rack::MockRequest.env_for("/").merge(headers) }

      it 'returns the load balancer IP' do
        client_ip = nil

        endpoint = proc do
          client_ip = Gitlab::SafeRequestStore[:client_ip]
          [200, {}, ["Hello"]]
        end

        described_class.new(endpoint).call(env)

        expect(client_ip).to eq(load_balancer_ip)
      end
    end

    context 'when RequestStore::Middleware is used' do
      around do |example|
        RequestStore::Middleware.new(-> (env) { example.run }).call({})
      end

      context 'request' do
        let(:ip) { '192.168.1.11' }

        before do
          allow_any_instance_of(Rack::Request).to receive(:ip).and_return(ip)
          described_class.new(app).call(env)
        end

        it { is_expected.to eq(ip) }
      end

      context 'before RequestContext middleware run' do
        it { is_expected.to be_nil }
      end
    end
  end
end