summaryrefslogtreecommitdiff
path: root/spec/services/google_cloud/fetch_google_ip_list_service_spec.rb
blob: ef77958fa602f0949f7f8d5af76861be9ae94f5b (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
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe GoogleCloud::FetchGoogleIpListService, :use_clean_rails_memory_store_caching,
:clean_gitlab_redis_rate_limiting, feature_category: :continuous_integration do
  include StubRequests

  let(:google_cloud_ips) { File.read(Rails.root.join('spec/fixtures/cdn/google_cloud.json')) }
  let(:headers) { { 'Content-Type' => 'application/json' } }

  subject { described_class.new.execute }

  before do
    WebMock.stub_request(:get, described_class::GOOGLE_IP_RANGES_URL)
      .to_return(status: 200, body: google_cloud_ips, headers: headers)
  end

  describe '#execute' do
    it 'returns a list of IPAddr subnets and caches the result' do
      expect(::ObjectStorage::CDN::GoogleIpCache).to receive(:update!).and_call_original
      expect(subject[:subnets]).to be_an(Array)
      expect(subject[:subnets]).to all(be_an(IPAddr))
    end

    shared_examples 'IP range retrieval failure' do
      it 'does not cache the result and logs an error' do
        expect(Gitlab::ErrorTracking).to receive(:log_exception).and_call_original
        expect(::ObjectStorage::CDN::GoogleIpCache).not_to receive(:update!)
        expect(subject[:subnets]).to be_nil
      end
    end

    context 'with rate limit in effect' do
      before do
        10.times { described_class.new.execute }
      end

      it 'returns rate limit error' do
        expect(subject[:status]).to eq(:error)
        expect(subject[:message]).to eq("#{described_class} was rate limited")
      end
    end

    context 'when the URL returns a 404' do
      before do
        WebMock.stub_request(:get, described_class::GOOGLE_IP_RANGES_URL).to_return(status: 404)
      end

      it_behaves_like 'IP range retrieval failure'
    end

    context 'when the URL returns too large of a payload' do
      before do
        stub_const("#{described_class}::RESPONSE_BODY_LIMIT", 300)
      end

      it_behaves_like 'IP range retrieval failure'
    end

    context 'when the URL returns HTML' do
      let(:headers) { { 'Content-Type' => 'text/html' } }

      it_behaves_like 'IP range retrieval failure'
    end

    context 'when the URL returns empty results' do
      let(:google_cloud_ips) { '{}' }

      it_behaves_like 'IP range retrieval failure'
    end
  end
end