Welcome to mirror list, hosted at ThFree Co, Russian Federation.

google_cdn.rb « cdn « object_storage « uploaders « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ea7683f131cf87c609803544e195a9a75f37ad53 (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
# rubocop:disable Naming/FileName
# frozen_string_literal: true

module ObjectStorage
  module CDN
    class GoogleCDN
      include Gitlab::Utils::StrongMemoize

      attr_reader :options

      def initialize(options)
        @options = HashWithIndifferentAccess.new(options.to_h)

        GoogleIpCache.async_refresh unless GoogleIpCache.ready?
      end

      def use_cdn?(request_ip)
        return false unless config_valid?

        ip = IPAddr.new(request_ip)

        return false if ip.private?

        !GoogleIpCache.google_ip?(request_ip)
      end

      def signed_url(path, expiry: 10.minutes)
        expiration = (Time.current + expiry).utc.to_i

        uri = Addressable::URI.parse(cdn_url)
        uri.path = path
        uri.query = "Expires=#{expiration}&KeyName=#{key_name}"

        signature = OpenSSL::HMAC.digest('SHA1', decoded_key, uri.to_s)
        encoded_signature = Base64.urlsafe_encode64(signature)

        uri.query += "&Signature=#{encoded_signature}"
        uri.to_s
      end

      private

      def config_valid?
        [key_name, decoded_key, cdn_url].all?(&:present?)
      end

      def key_name
        strong_memoize(:key_name) do
          options['key_name']
        end
      end

      def decoded_key
        strong_memoize(:decoded_key) do
          Base64.urlsafe_decode64(options['key']) if options['key']
        rescue ArgumentError
          Gitlab::ErrorTracking.log_exception(ArgumentError.new("Google CDN key is not base64-encoded"))
          nil
        end
      end

      def cdn_url
        strong_memoize(:cdn_url) do
          options['url']
        end
      end
    end
  end
end

# rubocop:enable Naming/FileName