auth.rb 10.3 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 30
      def omniauth_enabled?
        Gitlab.config.omniauth.enabled
31 32
      end

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

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

49
        rate_limit!(ip, success: result.success?, login: login)
50
        Gitlab::Auth::UniqueIpsLimiter.limit_user!(result.actor)
51

52
        return result if result.success? || authenticate_using_internal_or_ldap_password?
53 54 55

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

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

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

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

70
          break if user && !user.active?
71 72 73 74 75 76 77 78 79 80 81 82 83 84

          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
85
          end
86 87 88

          authenticators.compact!

89 90 91 92 93
          # 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
94 95 96
        end
      end

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

120 121
      private

122
      def authenticate_using_internal_or_ldap_password?
123
        Gitlab::CurrentSettings.password_authentication_enabled_for_git? || Gitlab::Auth::LDAP::Config.enabled?
124 125
      end

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

129
        return unless project && matched_login.present?
130 131 132

        underscored_service = matched_login['service'].underscore

133
        if Service.available_services_names.include?(underscored_service)
134 135
          # We treat underscored_service as a trusted input because it is included
          # in the Service.available_services_names whitelist.
136
          service = project.public_send("#{underscored_service}_service") # rubocop:disable GitlabSecurity/PublicSend
137

138
          if service && service.activated? && service.valid_token?(password)
139
            Gitlab::Auth::Result.new(nil, project, :ci, build_authentication_abilities)
140 141 142 143 144 145
          end
        end
      end

      def user_with_password_for_git(login, password)
        user = find_with_user_password(login, password)
146 147
        return unless user

148
        raise Gitlab::Auth::MissingPersonalAccessTokenError if user.two_factor_enabled?
149

Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
150
        Gitlab::Auth::Result.new(user, nil, :gitlab_or_ldap, full_authentication_abilities)
151 152
      end

153
      # rubocop: disable CodeReuse/ActiveRecord
154 155 156
      def oauth_access_token_check(login, password)
        if login == "oauth2" && password.present?
          token = Doorkeeper::AccessToken.by_token(password)
157

158
          if valid_oauth_token?(token)
159
            user = User.find_by(id: token.resource_owner_id)
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
160
            Gitlab::Auth::Result.new(user, nil, :oauth, full_authentication_abilities)
161
          end
162 163
        end
      end
164
      # rubocop: enable CodeReuse/ActiveRecord
165

Simon Vocella's avatar
Simon Vocella committed
166 167
      def personal_access_token_check(password)
        return unless password.present?
168

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

171
        if token && valid_scoped_token?(token, all_available_scopes)
172
          Gitlab::Auth::Result.new(token.user, nil, :personal_access_token, abilities_for_scopes(token.scopes))
173 174
        end
      end
Patricio Cano's avatar
Patricio Cano committed
175

176
      def valid_oauth_token?(token)
177
        token && token.accessible? && valid_scoped_token?(token, [:api])
178 179
      end

Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
180
      def valid_scoped_token?(token, scopes)
181 182 183
        AccessTokenValidationService.new(token).include_any_scope?(scopes)
      end

184 185 186
      def abilities_for_scopes(scopes)
        abilities_by_scope = {
          api: full_authentication_abilities,
187
          read_registry: [:read_container_image],
188 189
          read_repository: [:download_code],
          write_repository: [:download_code, :push_code]
190 191 192 193 194
        }

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

197
      # rubocop: disable CodeReuse/ActiveRecord
198
      def deploy_token_check(login, password)
199
        return unless password.present?
200

201
        token =
202 203
          DeployToken.active.find_by(token: password)

204 205
        return unless token && login
        return if login != token.username
206

207
        scopes = abilities_for_scopes(token.scopes)
208

209
        if valid_scoped_token?(token, all_available_scopes)
210
          Gitlab::Auth::Result.new(token, token.project, :deploy_token, scopes)
211 212
        end
      end
213
      # rubocop: enable CodeReuse/ActiveRecord
214

215
      def lfs_token_check(login, encoded_token, project)
216 217 218 219 220 221 222 223 224
        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

225
        return unless actor
226

227
        token_handler = Gitlab::LfsToken.new(actor)
228

229 230
        authentication_abilities =
          if token_handler.user?
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
231
            full_authentication_abilities
232 233
          elsif token_handler.deploy_key_pushable?(project)
            read_write_authentication_abilities
234
          else
235
            read_only_authentication_abilities
236 237
          end

238
        if token_handler.token_valid?(encoded_token)
239 240
          Gitlab::Auth::Result.new(actor, nil, token_handler.type, authentication_abilities)
        end
241 242
      end

243 244 245 246
      def build_access_token_check(login, password)
        return unless login == 'gitlab-ci-token'
        return unless password

247
        build = find_build_by_token(password)
248
        return unless build
Kamil Trzciński's avatar
Kamil Trzciński committed
249
        return unless build.project.builds_enabled?
250 251 252

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

260 261
      public

262
      def build_authentication_abilities
263 264
        [
          :read_project,
265
          :build_download_code,
266
          :build_read_container_image,
267
          :build_create_container_image
268 269 270
        ]
      end

271
      def read_only_authentication_abilities
272 273
        [
          :read_project,
274
          :download_code,
275 276 277 278
          :read_container_image
        ]
      end

279
      def read_write_authentication_abilities
280
        read_only_authentication_abilities + [
281
          :push_code,
282 283 284 285 286 287
          :create_container_image
        ]
      end

      def full_authentication_abilities
        read_write_authentication_abilities + [
288
          :admin_container_image
289 290
        ]
      end
291

292 293 294
      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
295
        scopes
296 297
      end

298 299 300 301
      def all_available_scopes
        non_admin_available_scopes + ADMIN_SCOPES
      end

302 303
      # Other available scopes
      def optional_scopes
304
        all_available_scopes + OPENID_SCOPES + PROFILE_SCOPES - DEFAULT_SCOPES
305 306 307 308 309 310 311
      end

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

        REGISTRY_SCOPES
      end
312 313 314

      private

315 316 317 318
      def non_admin_available_scopes
        API_SCOPES + REPOSITORY_SCOPES + registry_scopes
      end

319 320 321
      def find_build_by_token(token)
        ::Ci::Build.running.find_by_token(token)
      end
322
    end
323 324
  end
end