BigW Consortium Gitlab

trusted_proxies_spec.rb 2.11 KB
Newer Older
1 2 3 4 5 6 7 8
require 'spec_helper'

describe 'trusted_proxies', lib: true do
  context 'with default config' do
    before do
      set_trusted_proxies([])
    end

9
    it 'preserves private IPs' do
10 11
      request = stub_request('HTTP_X_FORWARDED_FOR' => '10.1.5.89')
      expect(request.remote_ip).to eq('10.1.5.89')
12
      expect(request.ip).to eq('10.1.5.89')
13 14
    end

15
    it 'filters out localhost' do
16 17
      request = stub_request('HTTP_X_FORWARDED_FOR' => '1.1.1.1, 10.1.5.89, 127.0.0.1')
      expect(request.remote_ip).to eq('10.1.5.89')
18
      expect(request.ip).to eq('10.1.5.89')
19
    end
20 21 22 23 24 25

    it 'filters out bad values' do
      request = stub_request('HTTP_X_FORWARDED_FOR' => '(null), 10.1.5.89')
      expect(request.remote_ip).to eq('10.1.5.89')
      expect(request.ip).to eq('10.1.5.89')
    end
26 27 28 29 30 31 32
  end

  context 'with private IP ranges added' do
    before do
      set_trusted_proxies([ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16" ])
    end

33
    it 'filters out private and local IPs' do
34 35
      request = stub_request('HTTP_X_FORWARDED_FOR' => '1.2.3.6, 1.1.1.1, 10.1.5.89, 127.0.0.1')
      expect(request.remote_ip).to eq('1.1.1.1')
36
      expect(request.ip).to eq('1.1.1.1')
37 38 39 40 41 42 43 44
    end
  end

  context 'with proxy IP added' do
    before do
      set_trusted_proxies([ "60.98.25.47" ])
    end

45
    it 'filters out proxy IP' do
46 47
      request = stub_request('HTTP_X_FORWARDED_FOR' => '1.2.3.6, 1.1.1.1, 60.98.25.47, 127.0.0.1')
      expect(request.remote_ip).to eq('1.1.1.1')
48
      expect(request.ip).to eq('1.1.1.1')
49
    end
50 51 52 53 54 55

    it 'handles invalid ip addresses' do
      request = stub_request('HTTP_X_FORWARDED_FOR' => '(null), 1.1.1.1:12345, 1.1.1.1')
      expect(request.remote_ip).to eq('1.1.1.1')
      expect(request.ip).to eq('1.1.1.1')
    end
56 57 58 59 60 61 62 63 64 65 66 67
  end

  def stub_request(headers = {})
    ActionDispatch::RemoteIp.new(Proc.new { }, false, Rails.application.config.action_dispatch.trusted_proxies).call(headers)
    ActionDispatch::Request.new(headers)
  end

  def set_trusted_proxies(proxies = [])
    stub_config_setting('trusted_proxies' => proxies)
    load File.join(__dir__, '../../config/initializers/trusted_proxies.rb')
  end
end