helpers.rb 2.2 KB
Newer Older
1 2 3
module Ci
  module API
    module Helpers
4 5
      BUILD_TOKEN_HEADER = "HTTP_BUILD_TOKEN"
      BUILD_TOKEN_PARAM = :token
6
      UPDATE_RUNNER_EVERY = 10 * 60
7

8
      def authenticate_runners!
9
        forbidden! unless runner_registration_token_valid?
10 11 12 13 14 15
      end

      def authenticate_runner!
        forbidden! unless current_runner
      end

16
      def authenticate_build_token!(build)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
17
        forbidden! unless build_token_valid?(build)
18 19
      end

20
      def runner_registration_token_valid?
21 22 23 24 25
        ActiveSupport::SecurityUtils.variable_size_secure_compare(
          params[:token],
          current_application_settings.runners_registration_token)
      end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
26
      def build_token_valid?(build)
27 28 29 30
        token = (params[BUILD_TOKEN_PARAM] || env[BUILD_TOKEN_HEADER]).to_s

        # We require to also check `runners_token` to maintain compatibility with old version of runners
        token && (build.valid_token?(token) || build.project.valid_runners_token?(token))
31 32
      end

33
      def update_runner_info
34
        return unless update_runner?
35 36 37 38

        current_runner.contacted_at = Time.now
        current_runner.assign_attributes(get_runner_version_from_params)
        current_runner.save if current_runner.changed?
39 40
      end

41 42 43 44 45 46 47 48 49 50
      def update_runner?
        # Use a random threshold to prevent beating DB updates.
        # It generates a distribution between [40m, 80m].
        #
        contacted_at_max_age = UPDATE_RUNNER_EVERY + Random.rand(UPDATE_RUNNER_EVERY)

        current_runner.contacted_at.nil? ||
          (Time.now - current_runner.contacted_at) >= contacted_at_max_age
      end

51 52 53 54 55 56 57 58
      def build_not_found!
        if headers['User-Agent'].match(/gitlab-ci-multi-runner \d+\.\d+\.\d+(~beta\.\d+\.g[0-9a-f]+)? /)
          no_content!
        else
          not_found!
        end
      end

Valery Sizov's avatar
Valery Sizov committed
59 60 61 62
      def current_runner
        @runner ||= Runner.find_by_token(params[:token].to_s)
      end

63
      def get_runner_version_from_params
64
        return unless params["info"].present?
65 66 67
        attributes_for_keys(["name", "version", "revision", "platform", "architecture"], params["info"])
      end

68 69 70
      def max_artifacts_size
        current_application_settings.max_artifacts_size.megabytes.to_i
      end
71 72 73
    end
  end
end