container_registry_authentication_service.rb 2.1 KB
Newer Older
1 2
module Auth
  class ContainerRegistryAuthenticationService < BaseService
3 4
    AUDIENCE = 'container_registry'

5
    def execute
6 7
      return error('not found', 404) unless registry.enabled

8 9 10 11
      if params[:offline_token]
        return error('forbidden', 403) unless current_user
      end

K
Kamil Trzcinski 已提交
12
      return error('forbidden', 401) unless scope
13

K
Kamil Trzcinski 已提交
14
      { token: authorized_token(scope).encoded }
15 16
    end

17 18 19 20 21 22 23 24 25 26 27
    def self.full_access_token(*names)
      registry = Gitlab.config.registry
      token = ::JWT::RSAToken.new(registry.key)
      token.issuer = registry.issuer
      token.audience = AUDIENCE
      token[:access] = names.map do |name|
        { type: 'repository', name: name, actions: %w(pull push) }
      end
      token.encoded
    end

28 29
    private

K
Kamil Trzcinski 已提交
30 31
    def authorized_token(*accesses)
      token = JSONWebToken::RSAToken.new(registry.key)
32 33 34
      token.issuer = registry.issuer
      token.audience = params[:service]
      token.subject = current_user.try(:username)
K
Kamil Trzcinski 已提交
35
      token[:access] = accesses
36 37 38
      token
    end

K
Kamil Trzcinski 已提交
39
    def scope
40 41
      return unless params[:scope]

K
Kamil Trzcinski 已提交
42
      @scope ||= process_scope(params[:scope])
43 44 45 46 47
    end

    def process_scope(scope)
      type, name, actions = scope.split(':', 3)
      actions = actions.split(',')
K
Kamil Trzcinski 已提交
48
      return unless type == 'repository'
49

K
Kamil Trzcinski 已提交
50
      process_repository_access(type, name, actions)
51 52 53 54 55 56 57 58 59 60 61 62 63 64
    end

    def process_repository_access(type, name, actions)
      requested_project = Project.find_with_namespace(name)
      return unless requested_project

      actions = actions.select do |action|
        can_access?(requested_project, action)
      end

      { type: type, name: name, actions: actions } if actions.present?
    end

    def can_access?(requested_project, requested_action)
K
Kamil Trzcinski 已提交
65 66
      return false unless requested_project.container_registry_enabled?

67 68
      case requested_action
      when 'pull'
K
Kamil Trzcinski 已提交
69
        requested_project == project || can?(current_user, :read_container_image, requested_project)
70
      when 'push'
K
Kamil Trzcinski 已提交
71
        requested_project == project || can?(current_user, :create_container_image, requested_project)
72 73 74 75 76 77 78 79 80 81
      else
        false
      end
    end

    def registry
      Gitlab.config.registry
    end
  end
end