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

5 6
    REGISTRY_SCOPES = [:read_registry].freeze

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

10
    # Scopes used for OpenID Connect
11 12
    OPENID_SCOPES = [:openid].freeze

13
    # Default scopes for OAuth applications that don't define their own
D
Douwe Maan 已提交
14
    DEFAULT_SCOPES = [:api].freeze
15

16 17
    AVAILABLE_SCOPES = (API_SCOPES + REGISTRY_SCOPES).freeze

18
    # Other available scopes
19
    OPTIONAL_SCOPES = (AVAILABLE_SCOPES + OPENID_SCOPES - DEFAULT_SCOPES).freeze
20

21
    class << self
22
      def find_for_git_client(login, password, project:, ip:)
23 24
        raise "Must provide an IP for rate limiting" if ip.nil?

25 26 27
        # `user_with_password_for_git` should be the last check
        # because it's the most expensive, especially when LDAP
        # is enabled.
28
        result =
29
          service_request_check(login, password, project) ||
30
          build_access_token_check(login, password) ||
31
          lfs_token_check(login, password) ||
32
          oauth_access_token_check(login, password) ||
S
Simon Vocella 已提交
33
          personal_access_token_check(password) ||
34
          user_with_password_for_git(login, password) ||
35
          Gitlab::Auth::Result.new
36

37
        rate_limit!(ip, success: result.success?, login: login)
38
        Gitlab::Auth::UniqueIpsLimiter.limit_user!(result.actor)
39

40
        result
41 42
      end

43
      def find_with_user_password(login, password)
44 45 46
        # Avoid resource intensive login checks if password is not provided
        return unless password.present?

47 48
        Gitlab::Auth::UniqueIpsLimiter.limit_user! do
          user = User.by_login(login)
49

50 51 52 53
          # 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
54
            return unless Gitlab::LDAP::Config.enabled?
55

56 57
            Gitlab::LDAP::Authentication.login(login, password)
          else
58
            user if user.active? && user.valid_password?(password)
59
          end
60 61 62
        end
      end

J
Jacob Vosmaer 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
      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

84 85
      private

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

89
        return unless project && matched_login.present?
90 91 92

        underscored_service = matched_login['service'].underscore

93
        if Service.available_services_names.include?(underscored_service)
94 95
          # We treat underscored_service as a trusted input because it is included
          # in the Service.available_services_names whitelist.
J
Jacob Vosmaer 已提交
96
          service = project.public_send("#{underscored_service}_service")
97

98
          if service && service.activated? && service.valid_token?(password)
99
            Gitlab::Auth::Result.new(nil, project, :ci, build_authentication_abilities)
100 101 102 103 104 105
          end
        end
      end

      def user_with_password_for_git(login, password)
        user = find_with_user_password(login, password)
106 107
        return unless user

108
        raise Gitlab::Auth::MissingPersonalTokenError if user.two_factor_enabled?
109

Z
Z.J. van de Weg 已提交
110
        Gitlab::Auth::Result.new(user, nil, :gitlab_or_ldap, full_authentication_abilities)
111 112
      end

113 114 115
      def oauth_access_token_check(login, password)
        if login == "oauth2" && password.present?
          token = Doorkeeper::AccessToken.by_token(password)
116

117
          if valid_oauth_token?(token)
118
            user = User.find_by(id: token.resource_owner_id)
Z
Z.J. van de Weg 已提交
119
            Gitlab::Auth::Result.new(user, nil, :oauth, full_authentication_abilities)
120
          end
121 122
        end
      end
123

S
Simon Vocella 已提交
124 125
      def personal_access_token_check(password)
        return unless password.present?
126

127
        token = PersonalAccessTokensFinder.new(state: 'active').find_by(token: password)
S
Simon Vocella 已提交
128

Z
Z.J. van de Weg 已提交
129
        if token && valid_scoped_token?(token, AVAILABLE_SCOPES.map(&:to_s))
130
          Gitlab::Auth::Result.new(token.user, nil, :personal_token, abilities_for_scope(token.scopes))
131 132
        end
      end
P
Patricio Cano 已提交
133

134
      def valid_oauth_token?(token)
Z
Z.J. van de Weg 已提交
135
        token && token.accessible? && valid_scoped_token?(token, ["api"])
136 137
      end

Z
Z.J. van de Weg 已提交
138
      def valid_scoped_token?(token, scopes)
139 140 141 142
        AccessTokenValidationService.new(token).include_any_scope?(scopes)
      end

      def abilities_for_scope(scopes)
Z
Z.J. van de Weg 已提交
143 144 145
        scopes.map do |scope|
          self.public_send(:"#{scope}_scope_authentication_abilities")
        end.flatten.uniq
146 147
      end

148 149 150 151 152 153 154 155 156 157
      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

158
        return unless actor
159

160
        token_handler = Gitlab::LfsToken.new(actor)
161

162 163
        authentication_abilities =
          if token_handler.user?
Z
Z.J. van de Weg 已提交
164
            full_authentication_abilities
165
          else
Z
Z.J. van de Weg 已提交
166
            read_authentication_abilities
167 168
          end

169 170 171
        if Devise.secure_compare(token_handler.token, password)
          Gitlab::Auth::Result.new(actor, nil, token_handler.type, authentication_abilities)
        end
172 173
      end

174 175 176 177
      def build_access_token_check(login, password)
        return unless login == 'gitlab-ci-token'
        return unless password

178
        build = ::Ci::Build.running.find_by_token(password)
179
        return unless build
K
Kamil Trzcinski 已提交
180
        return unless build.project.builds_enabled?
181 182 183

        if build.user
          # If user is assigned to build, use restricted credentials of user
184
          Gitlab::Auth::Result.new(build.user, build.project, :build, build_authentication_abilities)
185 186
        else
          # Otherwise use generic CI credentials (backward compatibility)
187
          Gitlab::Auth::Result.new(nil, build.project, :ci, build_authentication_abilities)
188 189
        end
      end
190

191 192
      public

193
      def build_authentication_abilities
194 195
        [
          :read_project,
196 197 198
          :build_download_code,
          :build_read_container_image,
          :build_create_container_image
199 200 201
        ]
      end

Z
Z.J. van de Weg 已提交
202
      def read_authentication_abilities
203 204
        [
          :read_project,
205
          :download_code,
206 207 208 209
          :read_container_image
        ]
      end

Z
Z.J. van de Weg 已提交
210 211
      def full_authentication_abilities
        read_authentication_abilities + [
212
          :push_code,
213
          :create_container_image
214 215
        ]
      end
Z
Z.J. van de Weg 已提交
216 217 218 219 220 221 222 223 224 225
      alias_method :api_scope_authentication_abilities, :full_authentication_abilities

      def read_registry_scope_authentication_abilities
        [:read_container_image]
      end

      # The currently used auth method doesn't allow any actions for this scope
      def read_user_scope_authentication_abilities
        []
      end
226
    end
D
Dmitriy Zaporozhets 已提交
227 228
  end
end