auth.rb 6.1 KB
Newer Older
D
Dmitriy Zaporozhets 已提交
1
module Gitlab
2
  module Auth
3 4
    class MissingPersonalTokenError < StandardError; end

D
Douwe Maan 已提交
5 6
    SCOPES = [:api, :read_user].freeze
    DEFAULT_SCOPES = [:api].freeze
7 8
    OPTIONAL_SCOPES = SCOPES - DEFAULT_SCOPES

9
    class << self
10
      def find_for_git_client(login, password, project:, ip:)
11 12
        raise "Must provide an IP for rate limiting" if ip.nil?

13 14 15
        # `user_with_password_for_git` should be the last check
        # because it's the most expensive, especially when LDAP
        # is enabled.
16
        result =
17
          service_request_check(login, password, project) ||
18
          build_access_token_check(login, password) ||
19
          lfs_token_check(login, password) ||
20 21
          oauth_access_token_check(login, password) ||
          user_with_password_for_git(login, password) ||
S
Simon Vocella 已提交
22
          personal_access_token_check(password) ||
23
          Gitlab::Auth::Result.new
24

25
        rate_limit!(ip, success: result.success?, login: login)
26

27
        result
28 29
      end

30
      def find_with_user_password(login, password)
31 32 33 34 35 36 37 38 39 40 41 42 43 44
        user = User.by_login(login)

        # If no user is found, or it's an LDAP server, try LDAP.
        #   LDAP users are only authenticated via LDAP
        if user.nil? || user.ldap_user?
          # Second chance - try LDAP authentication
          return nil unless Gitlab::LDAP::Config.enabled?

          Gitlab::LDAP::Authentication.login(login, password)
        else
          user if user.valid_password?(password)
        end
      end

J
Jacob Vosmaer 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
      def rate_limit!(ip, success:, login:)
        rate_limiter = Gitlab::Auth::IpRateLimiter.new(ip)
        return unless rate_limiter.enabled?

        if success
          # Repeated login 'failures' are normal behavior for some Git clients so
          # it is important to reset the ban counter once the client has proven
          # they are not a 'bad guy'.
          rate_limiter.reset!
        else
          # Register a login failure so that Rack::Attack can block the next
          # request from this IP if needed.
          rate_limiter.register_fail!

          if rate_limiter.banned?
            Rails.logger.info "IP #{ip} failed to login " \
              "as #{login} but has been temporarily banned from Git auth"
          end
        end
      end

66 67
      private

68
      def service_request_check(login, password, project)
69 70
        matched_login = /(?<service>^[a-zA-Z]*-ci)-token$/.match(login)

71
        return unless project && matched_login.present?
72 73 74

        underscored_service = matched_login['service'].underscore

75
        if Service.available_services_names.include?(underscored_service)
76 77
          # We treat underscored_service as a trusted input because it is included
          # in the Service.available_services_names whitelist.
J
Jacob Vosmaer 已提交
78
          service = project.public_send("#{underscored_service}_service")
79

80
          if service && service.activated? && service.valid_token?(password)
81
            Gitlab::Auth::Result.new(nil, project, :ci, build_authentication_abilities)
82 83 84 85 86 87
          end
        end
      end

      def user_with_password_for_git(login, password)
        user = find_with_user_password(login, password)
88 89
        return unless user

90
        raise Gitlab::Auth::MissingPersonalTokenError if user.two_factor_enabled?
91

92
        Gitlab::Auth::Result.new(user, nil, :gitlab_or_ldap, full_authentication_abilities)
93 94
      end

95 96 97
      def oauth_access_token_check(login, password)
        if login == "oauth2" && password.present?
          token = Doorkeeper::AccessToken.by_token(password)
98
          if valid_oauth_token?(token)
99
            user = User.find_by(id: token.resource_owner_id)
100
            Gitlab::Auth::Result.new(user, nil, :oauth, read_authentication_abilities)
101
          end
102 103
        end
      end
104

S
Simon Vocella 已提交
105 106
      def personal_access_token_check(password)
        return unless password.present?
107

108
        token = PersonalAccessTokensFinder.new(state: 'active').execute(token: password)
S
Simon Vocella 已提交
109

110
        if token && valid_api_token?(token)
S
Simon Vocella 已提交
111
          Gitlab::Auth::Result.new(token.user, nil, :personal_token, full_authentication_abilities)
112 113
        end
      end
P
Patricio Cano 已提交
114

115
      def valid_oauth_token?(token)
116
        token && token.accessible? && valid_api_token?(token)
117 118
      end

119
      def valid_api_token?(token)
120
        AccessTokenValidationService.new(token).include_any_scope?(['api'])
121 122
      end

123 124 125 126 127 128 129 130 131 132
      def lfs_token_check(login, password)
        deploy_key_matches = login.match(/\Alfs\+deploy-key-(\d+)\z/)

        actor =
          if deploy_key_matches
            DeployKey.find(deploy_key_matches[1])
          else
            User.by_login(login)
          end

133
        return unless actor
134

135
        token_handler = Gitlab::LfsToken.new(actor)
136

137 138 139 140 141 142 143
        authentication_abilities =
          if token_handler.user?
            full_authentication_abilities
          else
            read_authentication_abilities
          end

144 145 146
        if Devise.secure_compare(token_handler.token, password)
          Gitlab::Auth::Result.new(actor, nil, token_handler.type, authentication_abilities)
        end
147 148
      end

149 150 151 152
      def build_access_token_check(login, password)
        return unless login == 'gitlab-ci-token'
        return unless password

153
        build = ::Ci::Build.running.find_by_token(password)
154
        return unless build
K
Kamil Trzcinski 已提交
155
        return unless build.project.builds_enabled?
156 157 158

        if build.user
          # If user is assigned to build, use restricted credentials of user
159
          Gitlab::Auth::Result.new(build.user, build.project, :build, build_authentication_abilities)
160 161
        else
          # Otherwise use generic CI credentials (backward compatibility)
162
          Gitlab::Auth::Result.new(nil, build.project, :ci, build_authentication_abilities)
163 164
        end
      end
165

166 167
      public

168
      def build_authentication_abilities
169 170
        [
          :read_project,
171 172 173
          :build_download_code,
          :build_read_container_image,
          :build_create_container_image
174 175 176
        ]
      end

177
      def read_authentication_abilities
178 179
        [
          :read_project,
180
          :download_code,
181 182 183 184
          :read_container_image
        ]
      end

185 186
      def full_authentication_abilities
        read_authentication_abilities + [
187
          :push_code,
188
          :create_container_image
189 190
        ]
      end
191
    end
D
Dmitriy Zaporozhets 已提交
192 193
  end
end