PageRenderTime 54ms CodeModel.GetById 23ms app.highlight 29ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/api/helpers.rb

https://gitlab.com/alexkeramidas/gitlab-ce
Ruby | 499 lines | 369 code | 107 blank | 23 comment | 45 complexity | af568c08300556a93f0d77382010d269 MD5 | raw file
  1module API
  2  module Helpers
  3    include Gitlab::Utils
  4    include Helpers::Pagination
  5
  6    SUDO_HEADER = "HTTP_SUDO".freeze
  7    SUDO_PARAM = :sudo
  8    API_USER_ENV = 'gitlab.api.user'.freeze
  9
 10    def declared_params(options = {})
 11      options = { include_parent_namespaces: false }.merge(options)
 12      declared(params, options).to_h.symbolize_keys
 13    end
 14
 15    def check_unmodified_since!(last_modified)
 16      if_unmodified_since = Time.parse(headers['If-Unmodified-Since']) rescue nil
 17
 18      if if_unmodified_since && last_modified && last_modified > if_unmodified_since
 19        render_api_error!('412 Precondition Failed', 412)
 20      end
 21    end
 22
 23    def destroy_conditionally!(resource, last_updated: nil)
 24      last_updated ||= resource.updated_at
 25
 26      check_unmodified_since!(last_updated)
 27
 28      status 204
 29
 30      if block_given?
 31        yield resource
 32      else
 33        resource.destroy
 34      end
 35    end
 36
 37    # rubocop:disable Gitlab/ModuleWithInstanceVariables
 38    # We can't rewrite this with StrongMemoize because `sudo!` would
 39    # actually write to `@current_user`, and `sudo?` would immediately
 40    # call `current_user` again which reads from `@current_user`.
 41    # We should rewrite this in a way that using StrongMemoize is possible
 42    def current_user
 43      return @current_user if defined?(@current_user)
 44
 45      @current_user = initial_current_user
 46
 47      Gitlab::I18n.locale = @current_user&.preferred_language
 48
 49      sudo!
 50
 51      validate_access_token!(scopes: scopes_registered_for_endpoint) unless sudo?
 52
 53      save_current_user_in_env(@current_user) if @current_user
 54
 55      @current_user
 56    end
 57    # rubocop:enable Gitlab/ModuleWithInstanceVariables
 58
 59    def save_current_user_in_env(user)
 60      env[API_USER_ENV] = { user_id: user.id, username: user.username }
 61    end
 62
 63    def sudo?
 64      initial_current_user != current_user
 65    end
 66
 67    def user_namespace
 68      @user_namespace ||= find_namespace!(params[:id])
 69    end
 70
 71    def user_group
 72      @group ||= find_group!(params[:id])
 73    end
 74
 75    def user_project
 76      @project ||= find_project!(params[:id])
 77    end
 78
 79    def wiki_page
 80      page = ProjectWiki.new(user_project, current_user).find_page(params[:slug])
 81
 82      page || not_found!('Wiki Page')
 83    end
 84
 85    def available_labels_for(label_parent)
 86      search_params = { include_ancestor_groups: true }
 87
 88      if label_parent.is_a?(Project)
 89        search_params[:project_id] = label_parent.id
 90      else
 91        search_params.merge!(group_id: label_parent.id, only_group_labels: true)
 92      end
 93
 94      LabelsFinder.new(current_user, search_params).execute
 95    end
 96
 97    def find_user(id)
 98      if id =~ /^\d+$/
 99        User.find_by(id: id)
100      else
101        User.find_by(username: id)
102      end
103    end
104
105    def find_project(id)
106      if id.is_a?(Integer) || id =~ /^\d+$/
107        Project.find_by(id: id)
108      elsif id.include?("/")
109        Project.find_by_full_path(id)
110      end
111    end
112
113    def find_project!(id)
114      project = find_project(id)
115
116      if can?(current_user, :read_project, project)
117        project
118      else
119        not_found!('Project')
120      end
121    end
122
123    def find_group(id)
124      if id.to_s =~ /^\d+$/
125        Group.find_by(id: id)
126      else
127        Group.find_by_full_path(id)
128      end
129    end
130
131    def find_group!(id)
132      group = find_group(id)
133
134      if can?(current_user, :read_group, group)
135        group
136      else
137        not_found!('Group')
138      end
139    end
140
141    def find_namespace(id)
142      if id.to_s =~ /^\d+$/
143        Namespace.find_by(id: id)
144      else
145        Namespace.find_by_full_path(id)
146      end
147    end
148
149    def find_namespace!(id)
150      namespace = find_namespace(id)
151
152      if can?(current_user, :read_namespace, namespace)
153        namespace
154      else
155        not_found!('Namespace')
156      end
157    end
158
159    def find_project_label(id)
160      labels = available_labels_for(user_project)
161      label = labels.find_by_id(id) || labels.find_by_title(id)
162
163      label || not_found!('Label')
164    end
165
166    def find_project_issue(iid)
167      IssuesFinder.new(current_user, project_id: user_project.id).find_by!(iid: iid)
168    end
169
170    def find_project_merge_request(iid)
171      MergeRequestsFinder.new(current_user, project_id: user_project.id).find_by!(iid: iid)
172    end
173
174    def find_project_commit(id)
175      user_project.commit_by(oid: id)
176    end
177
178    def find_project_snippet(id)
179      finder_params = { project: user_project }
180      SnippetsFinder.new(current_user, finder_params).find(id)
181    end
182
183    def find_merge_request_with_access(iid, access_level = :read_merge_request)
184      merge_request = user_project.merge_requests.find_by!(iid: iid)
185      authorize! access_level, merge_request
186      merge_request
187    end
188
189    def find_build!(id)
190      user_project.builds.find(id.to_i)
191    end
192
193    def authenticate!
194      unauthorized! unless current_user
195    end
196
197    def authenticate_non_get!
198      authenticate! unless %w[GET HEAD].include?(route.request_method)
199    end
200
201    def authenticate_by_gitlab_shell_token!
202      input = params['secret_token'].try(:chomp)
203      unless Devise.secure_compare(secret_token, input)
204        unauthorized!
205      end
206    end
207
208    def authenticated_with_full_private_access!
209      authenticate!
210      forbidden! unless current_user.full_private_access?
211    end
212
213    def authenticated_as_admin!
214      authenticate!
215      forbidden! unless current_user.admin?
216    end
217
218    def authorize!(action, subject = :global)
219      forbidden! unless can?(current_user, action, subject)
220    end
221
222    def authorize_push_project
223      authorize! :push_code, user_project
224    end
225
226    def authorize_admin_project
227      authorize! :admin_project, user_project
228    end
229
230    def authorize_read_builds!
231      authorize! :read_build, user_project
232    end
233
234    def authorize_update_builds!
235      authorize! :update_build, user_project
236    end
237
238    def require_gitlab_workhorse!
239      unless env['HTTP_GITLAB_WORKHORSE'].present?
240        forbidden!('Request should be executed via GitLab Workhorse')
241      end
242    end
243
244    def require_pages_enabled!
245      not_found! unless user_project.pages_available?
246    end
247
248    def require_pages_config_enabled!
249      not_found! unless Gitlab.config.pages.enabled
250    end
251
252    def can?(object, action, subject = :global)
253      Ability.allowed?(object, action, subject)
254    end
255
256    # Checks the occurrences of required attributes, each attribute must be present in the params hash
257    # or a Bad Request error is invoked.
258    #
259    # Parameters:
260    #   keys (required) - A hash consisting of keys that must be present
261    def required_attributes!(keys)
262      keys.each do |key|
263        bad_request!(key) unless params[key].present?
264      end
265    end
266
267    def attributes_for_keys(keys, custom_params = nil)
268      params_hash = custom_params || params
269      attrs = {}
270      keys.each do |key|
271        if params_hash[key].present? || (params_hash.key?(key) && params_hash[key] == false)
272          attrs[key] = params_hash[key]
273        end
274      end
275      ActionController::Parameters.new(attrs).permit!
276    end
277
278    def filter_by_iid(items, iid)
279      items.where(iid: iid)
280    end
281
282    def filter_by_search(items, text)
283      items.search(text)
284    end
285
286    # error helpers
287
288    def forbidden!(reason = nil)
289      message = ['403 Forbidden']
290      message << " - #{reason}" if reason
291      render_api_error!(message.join(' '), 403)
292    end
293
294    def bad_request!(attribute)
295      message = ["400 (Bad request)"]
296      message << "\"" + attribute.to_s + "\" not given" if attribute
297      render_api_error!(message.join(' '), 400)
298    end
299
300    def not_found!(resource = nil)
301      message = ["404"]
302      message << resource if resource
303      message << "Not Found"
304      render_api_error!(message.join(' '), 404)
305    end
306
307    def unauthorized!
308      render_api_error!('401 Unauthorized', 401)
309    end
310
311    def not_allowed!
312      render_api_error!('405 Method Not Allowed', 405)
313    end
314
315    def conflict!(message = nil)
316      render_api_error!(message || '409 Conflict', 409)
317    end
318
319    def file_to_large!
320      render_api_error!('413 Request Entity Too Large', 413)
321    end
322
323    def not_modified!
324      render_api_error!('304 Not Modified', 304)
325    end
326
327    def no_content!
328      render_api_error!('204 No Content', 204)
329    end
330
331    def accepted!
332      render_api_error!('202 Accepted', 202)
333    end
334
335    def render_validation_error!(model)
336      if model.errors.any?
337        render_api_error!(model.errors.messages || '400 Bad Request', 400)
338      end
339    end
340
341    def render_spam_error!
342      render_api_error!({ error: 'Spam detected' }, 400)
343    end
344
345    def render_api_error!(message, status)
346      error!({ 'message' => message }, status, header)
347    end
348
349    def handle_api_exception(exception)
350      if sentry_enabled? && report_exception?(exception)
351        define_params_for_grape_middleware
352        sentry_context
353        Raven.capture_exception(exception, extra: params)
354      end
355
356      # lifted from https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb#L60
357      trace = exception.backtrace
358
359      message = "\n#{exception.class} (#{exception.message}):\n"
360      message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
361      message << "  " << trace.join("\n  ")
362
363      API.logger.add Logger::FATAL, message
364
365      response_message =
366        if Rails.env.test?
367          message
368        else
369          '500 Internal Server Error'
370        end
371
372      rack_response({ 'message' => response_message }.to_json, 500)
373    end
374
375    # project helpers
376
377    def reorder_projects(projects)
378      projects.reorder(params[:order_by] => params[:sort])
379    end
380
381    def project_finder_params
382      finder_params = {}
383      finder_params[:owned] = true if params[:owned].present?
384      finder_params[:non_public] = true if params[:membership].present?
385      finder_params[:starred] = true if params[:starred].present?
386      finder_params[:visibility_level] = Gitlab::VisibilityLevel.level_value(params[:visibility]) if params[:visibility]
387      finder_params[:archived] = params[:archived]
388      finder_params[:search] = params[:search] if params[:search]
389      finder_params[:user] = params.delete(:user) if params[:user]
390      finder_params[:custom_attributes] = params[:custom_attributes] if params[:custom_attributes]
391      finder_params
392    end
393
394    # file helpers
395
396    def present_disk_file!(path, filename, content_type = 'application/octet-stream')
397      filename ||= File.basename(path)
398      header['Content-Disposition'] = "attachment; filename=#{filename}"
399      header['Content-Transfer-Encoding'] = 'binary'
400      content_type content_type
401
402      # Support download acceleration
403      case headers['X-Sendfile-Type']
404      when 'X-Sendfile'
405        header['X-Sendfile'] = path
406        body
407      else
408        file path
409      end
410    end
411
412    def present_carrierwave_file!(file, supports_direct_download: true)
413      return not_found! unless file.exists?
414
415      if file.file_storage?
416        present_disk_file!(file.path, file.filename)
417      elsif supports_direct_download && file.class.direct_download_enabled?
418        redirect(file.url)
419      else
420        header(*Gitlab::Workhorse.send_url(file.url))
421        status :ok
422        body
423      end
424    end
425
426    private
427
428    # rubocop:disable Gitlab/ModuleWithInstanceVariables
429    def initial_current_user
430      return @initial_current_user if defined?(@initial_current_user)
431
432      begin
433        @initial_current_user = Gitlab::Auth::UniqueIpsLimiter.limit_user! { find_current_user! }
434      rescue Gitlab::Auth::UnauthorizedError
435        unauthorized!
436      end
437    end
438    # rubocop:enable Gitlab/ModuleWithInstanceVariables
439
440    def sudo!
441      return unless sudo_identifier
442
443      unauthorized! unless initial_current_user
444
445      unless initial_current_user.admin?
446        forbidden!('Must be admin to use sudo')
447      end
448
449      unless access_token
450        forbidden!('Must be authenticated using an OAuth or Personal Access Token to use sudo')
451      end
452
453      validate_access_token!(scopes: [:sudo])
454
455      sudoed_user = find_user(sudo_identifier)
456      not_found!("User with ID or username '#{sudo_identifier}'") unless sudoed_user
457
458      @current_user = sudoed_user # rubocop:disable Gitlab/ModuleWithInstanceVariables
459    end
460
461    def sudo_identifier
462      @sudo_identifier ||= params[SUDO_PARAM] || env[SUDO_HEADER]
463    end
464
465    def secret_token
466      Gitlab::Shell.secret_token
467    end
468
469    def send_git_blob(repository, blob)
470      env['api.format'] = :txt
471      content_type 'text/plain'
472      header(*Gitlab::Workhorse.send_git_blob(repository, blob))
473    end
474
475    def send_git_archive(repository, **kwargs)
476      header(*Gitlab::Workhorse.send_git_archive(repository, **kwargs))
477    end
478
479    def send_artifacts_entry(build, entry)
480      header(*Gitlab::Workhorse.send_artifacts_entry(build, entry))
481    end
482
483    # The Grape Error Middleware only has access to `env` but not `params` nor
484    # `request`. We workaround this by defining methods that returns the right
485    # values.
486    def define_params_for_grape_middleware
487      self.define_singleton_method(:request) { Rack::Request.new(env) }
488      self.define_singleton_method(:params) { request.params.symbolize_keys }
489    end
490
491    # We could get a Grape or a standard Ruby exception. We should only report anything that
492    # is clearly an error.
493    def report_exception?(exception)
494      return true unless exception.respond_to?(:status)
495
496      exception.status == 500
497    end
498  end
499end