runner.rb 1.78 KB
Newer Older
1
2
# frozen_string_literal: true

3
4
module API
  module Helpers
5
    module Runner
Tomasz Maczukin's avatar
Tomasz Maczukin committed
6
      JOB_TOKEN_HEADER = 'HTTP_JOB_TOKEN'.freeze
Tomasz Maczukin's avatar
Tomasz Maczukin committed
7
      JOB_TOKEN_PARAM = :token
Tomasz Maczukin's avatar
Tomasz Maczukin committed
8

9
      def runner_registration_token_valid?
Heinrich Lee Yu's avatar
Heinrich Lee Yu committed
10
        ActiveSupport::SecurityUtils.secure_compare(params[:token], Gitlab::CurrentSettings.runners_registration_token)
11
12
      end

13
14
      def authenticate_runner!
        forbidden! unless current_runner
15

16
17
        current_runner
          .update_cached_info(get_runner_details_from_request)
18
19
      end

20
21
22
23
24
25
      def get_runner_details_from_request
        return get_runner_ip unless params['info'].present?

        attributes_for_keys(%w(name version revision platform architecture), params['info'])
          .merge(get_runner_ip)
      end
26

27
      def get_runner_ip
28
        { ip_address: env["action_dispatch.remote_ip"].to_s || request.ip }
29
30
31
32
33
      end

      def current_runner
        @runner ||= ::Ci::Runner.find_by_token(params[:token].to_s)
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
34

Tomasz Maczukin's avatar
Tomasz Maczukin committed
35
36
37
38
39
      def validate_job!(job)
        not_found! unless job

        yield if block_given?

40
41
        project = job.project
        forbidden!('Project has been deleted!') if project.nil? || project.pending_delete?
Tomasz Maczukin's avatar
Tomasz Maczukin committed
42
43
        forbidden!('Job has been erased!') if job.erased?
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
44

45
46
47
      def authenticate_job!
        job = Ci::Build.find_by_id(params[:id])

Tomasz Maczukin's avatar
Tomasz Maczukin committed
48
49
50
        validate_job!(job) do
          forbidden! unless job_token_valid?(job)
        end
51
52

        job
Tomasz Maczukin's avatar
Tomasz Maczukin committed
53
54
55
56
57
58
      end

      def job_token_valid?(job)
        token = (params[JOB_TOKEN_PARAM] || env[JOB_TOKEN_HEADER]).to_s
        token && job.valid_token?(token)
      end
59
60

      def max_artifacts_size
61
        Gitlab::CurrentSettings.max_artifacts_size.megabytes.to_i
62
      end
63
64
65
66
67

      def job_forbidden!(job, reason)
        header 'Job-Status', job.status
        forbidden!(reason)
      end
68
69
    end
  end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
70
end