auth.rb 10.8 KB
Newer Older
1 2
# frozen_string_literal: true

3
module Gitlab
4
  module Auth
5
    MissingPersonalAccessTokenError = Class.new(StandardError)
6

7 8 9 10 11 12 13
    # Scopes used for GitLab API access
    API_SCOPES = [:api, :read_user].freeze

    # Scopes used for GitLab Repository access
    REPOSITORY_SCOPES = [:read_repository, :write_repository].freeze

    # Scopes used for GitLab Docker Registry access
14
    REGISTRY_SCOPES = [:read_registry].freeze
15

16 17
    # Scopes used for GitLab as admin
    ADMIN_SCOPES = [:sudo].freeze
18

19
    # Scopes used for OpenID Connect
20 21
    OPENID_SCOPES = [:openid].freeze

22 23 24
    # OpenID Connect profile scopes
    PROFILE_SCOPES = [:profile, :email].freeze

25
    # Default scopes for OAuth applications that don't define their own
26
    DEFAULT_SCOPES = [:api].freeze
27

28
    class << self
29
      prepend_if_ee('EE::Gitlab::Auth') # rubocop: disable Cop/InjectEnterpriseEditionModule
30

31 32
      def omniauth_enabled?
        Gitlab.config.omniauth.enabled
33 34
      end

35
      def find_for_git_client(login, password, project:, ip:)
36 37
        raise "Must provide an IP for rate limiting" if ip.nil?

38 39 40
        # `user_with_password_for_git` should be the last check
        # because it's the most expensive, especially when LDAP
        # is enabled.
41
        result =
42
          service_request_check(login, password, project) ||
43
          build_access_token_check(login, password) ||
44
          lfs_token_check(login, password, project) ||
45
          oauth_access_token_check(login, password) ||
Simon Vocella's avatar
Simon Vocella committed
46
          personal_access_token_check(password) ||
47
          deploy_token_check(login, password) ||
48
          user_with_password_for_git(login, password) ||
49
          Gitlab::Auth::Result.new
50

51
        rate_limit!(ip, success: result.success?, login: login) unless skip_rate_limit?(login: login)
52
        Gitlab::Auth::UniqueIpsLimiter.limit_user!(result.actor)
53

54
        return result if result.success? || authenticate_using_internal_or_ldap_password?
55 56 57

        # If sign-in is disabled and LDAP is not configured, recommend a
        # personal access token on failed auth attempts
58
        raise Gitlab::Auth::MissingPersonalAccessTokenError
59 60
      end

61
      def find_with_user_password(login, password)
62 63
        # Avoid resource intensive checks if login credentials are not provided
        return unless login.present? && password.present?
64

65 66 67 68
        # Nothing to do here if internal auth is disabled and LDAP is
        # not configured
        return unless authenticate_using_internal_or_ldap_password?

69 70
        Gitlab::Auth::UniqueIpsLimiter.limit_user! do
          user = User.by_login(login)
71

72
          break if user && !user.can?(:log_in)
73 74 75 76 77 78 79 80 81 82 83 84 85 86

          authenticators = []

          if user
            authenticators << Gitlab::Auth::OAuth::Provider.authentication(user, 'database')

            # Add authenticators for all identities if user is not nil
            user&.identities&.each do |identity|
              authenticators << Gitlab::Auth::OAuth::Provider.authentication(user, identity.provider)
            end
          else
            # If no user is provided, try LDAP.
            #   LDAP users are only authenticated via LDAP
            authenticators << Gitlab::Auth::LDAP::Authentication
87
          end
88 89 90

          authenticators.compact!

91 92 93 94 95
          # return found user that was authenticated first for given login credentials
          authenticators.find do |auth|
            authenticated_user = auth.login(login, password)
            break authenticated_user if authenticated_user
          end
96 97 98
        end
      end

99
      # rubocop:disable Gitlab/RailsLogger
Jacob Vosmaer's avatar
Jacob Vosmaer committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
      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
120
      # rubocop:enable Gitlab/RailsLogger
Jacob Vosmaer's avatar
Jacob Vosmaer committed
121

122 123
      private

124 125 126 127
      def skip_rate_limit?(login:)
        ::Ci::Build::CI_REGISTRY_USER == login
      end

128
      def authenticate_using_internal_or_ldap_password?
129
        Gitlab::CurrentSettings.password_authentication_enabled_for_git? || Gitlab::Auth::LDAP::Config.enabled?
130 131
      end

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

135
        return unless project && matched_login.present?
136 137 138

        underscored_service = matched_login['service'].underscore

139
        if Service.available_services_names.include?(underscored_service)
140 141
          # We treat underscored_service as a trusted input because it is included
          # in the Service.available_services_names whitelist.
142
          service = project.public_send("#{underscored_service}_service") # rubocop:disable GitlabSecurity/PublicSend
143

144
          if service && service.activated? && service.valid_token?(password)
145
            Gitlab::Auth::Result.new(nil, project, :ci, build_authentication_abilities)
146 147 148 149 150 151
          end
        end
      end

      def user_with_password_for_git(login, password)
        user = find_with_user_password(login, password)
152 153
        return unless user

154
        raise Gitlab::Auth::MissingPersonalAccessTokenError if user.two_factor_enabled?
155

156
        Gitlab::Auth::Result.new(user, nil, :gitlab_or_ldap, full_authentication_abilities)
157 158
      end

159
      # rubocop: disable CodeReuse/ActiveRecord
160 161 162
      def oauth_access_token_check(login, password)
        if login == "oauth2" && password.present?
          token = Doorkeeper::AccessToken.by_token(password)
163

164
          if valid_oauth_token?(token)
165
            user = User.find_by(id: token.resource_owner_id)
166
            Gitlab::Auth::Result.new(user, nil, :oauth, full_authentication_abilities)
167
          end
168 169
        end
      end
170
      # rubocop: enable CodeReuse/ActiveRecord
171

Simon Vocella's avatar
Simon Vocella committed
172 173
      def personal_access_token_check(password)
        return unless password.present?
174

175
        token = PersonalAccessTokensFinder.new(state: 'active').find_by_token(password)
Simon Vocella's avatar
Simon Vocella committed
176

177
        if token && valid_scoped_token?(token, all_available_scopes)
178
          Gitlab::Auth::Result.new(token.user, nil, :personal_access_token, abilities_for_scopes(token.scopes))
179 180
        end
      end
Patricio Cano's avatar
Patricio Cano committed
181

182
      def valid_oauth_token?(token)
183
        token && token.accessible? && valid_scoped_token?(token, [:api])
184 185
      end

Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
186
      def valid_scoped_token?(token, scopes)
187 188 189
        AccessTokenValidationService.new(token).include_any_scope?(scopes)
      end

190 191 192
      def abilities_for_scopes(scopes)
        abilities_by_scope = {
          api: full_authentication_abilities,
193
          read_registry: [:read_container_image],
194 195
          read_repository: [:download_code],
          write_repository: [:download_code, :push_code]
196 197 198 199 200
        }

        scopes.flat_map do |scope|
          abilities_by_scope.fetch(scope.to_sym, [])
        end.uniq
201 202
      end

203
      def deploy_token_check(login, password)
204
        return unless password.present?
205

206
        token = DeployToken.active.find_by_token(password)
207

208 209
        return unless token && login
        return if login != token.username
210

211
        scopes = abilities_for_scopes(token.scopes)
212

213
        if valid_scoped_token?(token, all_available_scopes)
214
          Gitlab::Auth::Result.new(token, token.project, :deploy_token, scopes)
215 216 217
        end
      end

218
      def lfs_token_check(login, encoded_token, project)
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        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

        return unless actor

        token_handler = Gitlab::LfsToken.new(actor)

        authentication_abilities =
          if token_handler.user?
234
            read_write_project_authentication_abilities
235 236
          elsif token_handler.deploy_key_pushable?(project)
            read_write_authentication_abilities
237
          else
238
            read_only_authentication_abilities
239 240
          end

241
        if token_handler.token_valid?(encoded_token)
242 243
          Gitlab::Auth::Result.new(actor, nil, token_handler.type, authentication_abilities)
        end
244 245
      end

246 247 248 249
      def build_access_token_check(login, password)
        return unless login == 'gitlab-ci-token'
        return unless password

250
        build = find_build_by_token(password)
251
        return unless build
Kamil Trzciński's avatar
Kamil Trzciński committed
252
        return unless build.project.builds_enabled?
253 254 255

        if build.user
          # If user is assigned to build, use restricted credentials of user
256
          Gitlab::Auth::Result.new(build.user, build.project, :build, build_authentication_abilities)
257 258
        else
          # Otherwise use generic CI credentials (backward compatibility)
259
          Gitlab::Auth::Result.new(nil, build.project, :ci, build_authentication_abilities)
260
        end
261
      end
262

263 264
      public

265
      def build_authentication_abilities
266 267
        [
          :read_project,
268 269
          :build_download_code,
          :build_read_container_image,
270 271
          :build_create_container_image,
          :build_destroy_container_image
272 273 274
        ]
      end

275
      def read_only_project_authentication_abilities
276 277
        [
          :read_project,
278 279 280 281 282 283 284 285 286 287 288 289
          :download_code
        ]
      end

      def read_write_project_authentication_abilities
        read_only_project_authentication_abilities + [
          :push_code
        ]
      end

      def read_only_authentication_abilities
        read_only_project_authentication_abilities + [
290 291 292 293
          :read_container_image
        ]
      end

294
      def read_write_authentication_abilities
295
        read_only_authentication_abilities + [
296
          :push_code,
297 298 299 300 301 302
          :create_container_image
        ]
      end

      def full_authentication_abilities
        read_write_authentication_abilities + [
303
          :admin_container_image
304 305
        ]
      end
306

307 308 309
      def available_scopes_for(current_user)
        scopes = non_admin_available_scopes
        scopes += ADMIN_SCOPES if current_user.admin?
Douwe Maan's avatar
Douwe Maan committed
310
        scopes
311 312
      end

313 314 315 316
      def all_available_scopes
        non_admin_available_scopes + ADMIN_SCOPES
      end

317 318
      # Other available scopes
      def optional_scopes
319
        all_available_scopes + OPENID_SCOPES + PROFILE_SCOPES - DEFAULT_SCOPES
320 321 322 323 324 325 326
      end

      def registry_scopes
        return [] unless Gitlab.config.registry.enabled

        REGISTRY_SCOPES
      end
327 328 329

      private

330 331 332 333
      def non_admin_available_scopes
        API_SCOPES + REPOSITORY_SCOPES + registry_scopes
      end

334 335 336
      def find_build_by_token(token)
        ::Ci::Build.running.find_by_token(token)
      end
337
    end
338 339
  end
end