auth.rb 6.5 KB
Newer Older
D
Dmitriy Zaporozhets 已提交
1
module Gitlab
2
  module Auth
3
    MissingPersonalTokenError = Class.new(StandardError)
4

5
    SCOPES = [:api, :read_user, :openid, :profile, :email].freeze
D
Douwe Maan 已提交
6
    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
          oauth_access_token_check(login, password) ||
21
          personal_access_token_check(login, password) ||
22
          user_with_password_for_git(login, password) ||
23
          Gitlab::Auth::Result.new
24

25
        rate_limit!(ip, success: result.success?, login: login)
26
        Gitlab::Auth::UniqueIpsLimiter.limit_user!(result.actor)
27

28
        result
29 30
      end

31
      def find_with_user_password(login, password)
32 33
        Gitlab::Auth::UniqueIpsLimiter.limit_user! do
          user = User.by_login(login)
34

35 36 37 38 39
          # 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?
40

41 42 43 44
            Gitlab::LDAP::Authentication.login(login, password)
          else
            user if user.valid_password?(password)
          end
45 46 47
        end
      end

J
Jacob Vosmaer 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
      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

69 70
      private

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

74
        return unless project && matched_login.present?
75 76 77

        underscored_service = matched_login['service'].underscore

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

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

      def user_with_password_for_git(login, password)
        user = find_with_user_password(login, password)
91 92
        return unless user

93
        raise Gitlab::Auth::MissingPersonalTokenError if user.two_factor_enabled?
94

95
        Gitlab::Auth::Result.new(user, nil, :gitlab_or_ldap, full_authentication_abilities)
96 97
      end

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

      def personal_access_token_check(login, password)
        if login && password
110
          token = PersonalAccessToken.active.find_by_token(password)
111
          validation = User.by_login(login)
112

113
          if valid_personal_access_token?(token, validation)
114 115
            Gitlab::Auth::Result.new(validation, nil, :personal_token, full_authentication_abilities)
          end
116 117
        end
      end
P
Patricio Cano 已提交
118

119
      def valid_oauth_token?(token)
120
        token && token.accessible? && valid_api_token?(token)
121 122 123
      end

      def valid_personal_access_token?(token, user)
124
        token && token.user == user && valid_api_token?(token)
125 126
      end

127
      def valid_api_token?(token)
128
        AccessTokenValidationService.new(token).include_any_scope?(['api'])
129 130
      end

131 132 133 134 135 136 137 138 139 140
      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

141
        return unless actor
142

143
        token_handler = Gitlab::LfsToken.new(actor)
144

145 146 147 148 149 150 151
        authentication_abilities =
          if token_handler.user?
            full_authentication_abilities
          else
            read_authentication_abilities
          end

152 153 154
        if Devise.secure_compare(token_handler.token, password)
          Gitlab::Auth::Result.new(actor, nil, token_handler.type, authentication_abilities)
        end
155 156
      end

157 158 159 160
      def build_access_token_check(login, password)
        return unless login == 'gitlab-ci-token'
        return unless password

161
        build = ::Ci::Build.running.find_by_token(password)
162
        return unless build
K
Kamil Trzcinski 已提交
163
        return unless build.project.builds_enabled?
164 165 166

        if build.user
          # If user is assigned to build, use restricted credentials of user
167
          Gitlab::Auth::Result.new(build.user, build.project, :build, build_authentication_abilities)
168 169
        else
          # Otherwise use generic CI credentials (backward compatibility)
170
          Gitlab::Auth::Result.new(nil, build.project, :ci, build_authentication_abilities)
171 172
        end
      end
173

174 175
      public

176
      def build_authentication_abilities
177 178
        [
          :read_project,
179 180 181
          :build_download_code,
          :build_read_container_image,
          :build_create_container_image
182 183 184
        ]
      end

185
      def read_authentication_abilities
186 187
        [
          :read_project,
188
          :download_code,
189 190 191 192
          :read_container_image
        ]
      end

193 194
      def full_authentication_abilities
        read_authentication_abilities + [
195
          :push_code,
196
          :create_container_image
197 198
        ]
      end
199
    end
D
Dmitriy Zaporozhets 已提交
200 201
  end
end