application_controller.rb 14.4 KB
Newer Older
1 2
# frozen_string_literal: true

3
require 'gon'
Jared Szechy's avatar
Jared Szechy committed
4
require 'fogbugz'
5

6
class ApplicationController < ActionController::Base
7
  include Gitlab::GonHelper
8 9
  include GitlabRoutingHelper
  include PageLayoutHelper
10
  include SafeParamsHelper
11
  include WorkhorseHelper
12
  include EnforcesTwoFactorAuthentication
13
  include WithPerformanceBar
14
  include SessionlessAuthentication
15 16 17
  # this can be removed after switching to rails 5
  # https://gitlab.com/gitlab-org/gitlab-ce/issues/51908
  include InvalidUTF8ErrorHandler unless Gitlab.rails5?
18

19
  before_action :authenticate_user!
20
  before_action :enforce_terms!, if: :should_enforce_terms?
tduehr's avatar
tduehr committed
21
  before_action :validate_user_service_ticket!
22 23
  before_action :check_password_expiration
  before_action :ldap_security_check
24
  before_action :sentry_context
25
  before_action :default_headers
26
  before_action :add_gon_variables, unless: [:peek_request?, :json_request?]
27 28
  before_action :configure_permitted_parameters, if: :devise_controller?
  before_action :require_email, unless: :devise_controller?
29
  before_action :set_usage_stats_consent_flag
30
  before_action :check_impersonation_availability
31

32 33
  around_action :set_locale

34
  after_action :set_page_title_header, if: :json_request?
35
  after_action :limit_unauthenticated_session_times
36

37
  protect_from_forgery with: :exception, prepend: true
38

39
  helper_method :can?
40 41 42 43
  helper_method :import_sources_enabled?, :github_import_enabled?,
    :gitea_import_enabled?, :github_import_configured?,
    :gitlab_import_enabled?, :gitlab_import_configured?,
    :bitbucket_import_enabled?, :bitbucket_import_configured?,
44
    :bitbucket_server_import_enabled?,
45 46 47
    :google_code_import_enabled?, :fogbugz_import_enabled?,
    :git_import_enabled?, :gitlab_project_import_enabled?,
    :manifest_import_enabled?
gitlabhq's avatar
gitlabhq committed
48

49 50
  DEFAULT_GITLAB_CACHE_CONTROL = "#{ActionDispatch::Http::Cache::Response::DEFAULT_CACHE_CONTROL}, no-store".freeze

51
  rescue_from Encoding::CompatibilityError do |exception|
Riyad Preukschas's avatar
Riyad Preukschas committed
52
    log_exception(exception)
Cyril's avatar
Cyril committed
53
    render "errors/encoding", layout: "errors", status: 500
54 55
  end

56
  rescue_from ActiveRecord::RecordNotFound do |exception|
Riyad Preukschas's avatar
Riyad Preukschas committed
57
    log_exception(exception)
58
    render_404
gitlabhq's avatar
gitlabhq committed
59 60
  end

61 62 63 64
  rescue_from(ActionController::UnknownFormat) do
    render_404
  end

65 66 67 68
  rescue_from Gitlab::Access::AccessDeniedError do |exception|
    render_403
  end

69
  rescue_from Gitlab::Auth::TooManyIps do |e|
70
    head :forbidden, retry_after: Gitlab::Auth::UniqueIpsLimiter.config.unique_ips_limit_time_window
71 72
  end

73
  rescue_from GRPC::Unavailable, Gitlab::Git::CommandError do |exception|
74 75 76 77 78 79 80
    log_exception(exception)

    headers['Retry-After'] = exception.retry_after if exception.respond_to?(:retry_after)

    render_503
  end

81 82 83 84
  def redirect_back_or_default(default: root_path, options: {})
    redirect_to request.referer.present? ? :back : default, options
  end

85 86 87 88
  def not_found
    render_404
  end

89 90 91 92
  def route_not_found
    if current_user
      not_found
    else
93
      authenticate_user!
94 95 96
    end
  end

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
  # By default, all sessions are given the same expiration time configured in
  # the session store (e.g. 1 week). However, unauthenticated users can
  # generate a lot of sessions, primarily for CSRF verification. It makes
  # sense to reduce the TTL for unauthenticated to something much lower than
  # the default (e.g. 1 hour) to limit Redis memory. In addition, Rails
  # creates a new session after login, so the short TTL doesn't even need to
  # be extended.
  def limit_unauthenticated_session_times
    return if current_user

    # Rack sets this header, but not all tests may have it: https://github.com/rack/rack/blob/fdcd03a3c5a1c51d1f96fc97f9dfa1a9deac0c77/lib/rack/session/abstract/id.rb#L251-L259
    return unless request.env['rack.session.options']

    # This works because Rack uses these options every time a request is handled:
    # https://github.com/rack/rack/blob/fdcd03a3c5a1c51d1f96fc97f9dfa1a9deac0c77/lib/rack/session/abstract/id.rb#L342
    request.env['rack.session.options'][:expire_after] = Settings.gitlab['unauthenticated_session_expire_delay']
  end

115 116 117 118 119 120 121 122 123
  def render(*args)
    super.tap do
      # Set a header for custom error pages to prevent them from being intercepted by gitlab-workhorse
      if response.content_type == 'text/html' && (400..599).cover?(response.status)
        response.headers['X-GitLab-Custom-Error'] = '1'
      end
    end
  end

Nihad Abbasov's avatar
Nihad Abbasov committed
124
  protected
gitlabhq's avatar
gitlabhq committed
125

126 127
  def append_info_to_payload(payload)
    super
128

129
    payload[:ua] = request.env["HTTP_USER_AGENT"]
130
    payload[:remote_ip] = request.remote_ip
131
    payload[Gitlab::CorrelationId::LOG_KEY] = Gitlab::CorrelationId.current_id
132

133 134 135 136 137
    logged_user = auth_user

    if logged_user.present?
      payload[:user_id] = logged_user.try(:id)
      payload[:username] = logged_user.try(:username)
138
    end
139 140 141 142

    if response.status == 422 && response.body.present? && response.content_type == 'application/json'.freeze
      payload[:response] = response.body
    end
143 144
  end

145
  ##
146
  # Controllers such as GitHttpController may use alternative methods
147 148
  # (e.g. tokens) to authenticate the user, whereas Devise sets current_user.
  #
149
  def auth_user
150
    if user_signed_in?
151 152 153 154
      current_user
    else
      try(:authenticated_user)
    end
155 156
  end

Riyad Preukschas's avatar
Riyad Preukschas committed
157
  def log_exception(exception)
158
    Gitlab::Sentry.track_acceptable_exception(exception)
Stan Hu's avatar
Stan Hu committed
159

160
    backtrace_cleaner = Gitlab.rails5? ? request.env["action_dispatch.backtrace_cleaner"] : env
161
    application_trace = ActionDispatch::ExceptionWrapper.new(backtrace_cleaner, exception).application_trace
162
    application_trace.map! { |t| "  #{t}\n" }
Riyad Preukschas's avatar
Riyad Preukschas committed
163 164 165
    logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  end

166
  def after_sign_in_path_for(resource)
167
    stored_location_for(:redirect) || stored_location_for(resource) || root_path
randx's avatar
randx committed
168 169
  end

170
  def after_sign_out_path_for(resource)
171
    Gitlab::CurrentSettings.after_sign_out_path.presence || new_user_session_path
172 173
  end

174
  def can?(object, action, subject = :global)
175
    Ability.allowed?(object, action, subject)
gitlabhq's avatar
gitlabhq committed
176 177
  end

178
  def access_denied!(message = nil, status = nil)
179 180 181
    # If we display a custom access denied message to the user, we don't want to
    # hide existence of the resource, rather tell them they cannot access it using
    # the provided message
182
    status ||= message.present? ? :forbidden : :not_found
183

Fatih Acet's avatar
Fatih Acet committed
184
    respond_to do |format|
185
      format.any { head status }
186 187 188
      format.html do
        render "errors/access_denied",
               layout: "errors",
189
               status: status,
190 191
               locals: { message: message }
      end
Fatih Acet's avatar
Fatih Acet committed
192
    end
193 194 195
  end

  def git_not_found!
196
    render "errors/git_not_found.html", layout: "errors", status: 404
gitlabhq's avatar
gitlabhq committed
197 198
  end

199
  def render_403
Paul Slaughter's avatar
Paul Slaughter committed
200 201 202 203
    respond_to do |format|
      format.any { head :forbidden }
      format.html { render "errors/access_denied", layout: "errors", status: 403 }
    end
gitlabhq's avatar
gitlabhq committed
204
  end
gitlabhq's avatar
gitlabhq committed
205

206
  def render_404
207
    respond_to do |format|
Paul Slaughter's avatar
Paul Slaughter committed
208
      format.html { render "errors/not_found", layout: "errors", status: 404 }
209 210
      # Prevent the Rails CSRF protector from thinking a missing .js file is a JavaScript file
      format.js { render json: '', status: :not_found, content_type: 'application/json' }
Sean McGivern's avatar
Sean McGivern committed
211
      format.any { head :not_found }
212
    end
213 214
  end

215 216 217 218
  def respond_422
    head :unprocessable_entity
  end

219 220 221 222 223 224 225 226 227 228 229 230 231
  def render_503
    respond_to do |format|
      format.html do
        render(
          file: Rails.root.join("public", "503"),
          layout: false,
          status: :service_unavailable
        )
      end
      format.any { head :service_unavailable }
    end
  end

232 233 234 235 236
  def no_cache_headers
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  end
237

238 239 240
  def default_headers
    headers['X-Frame-Options'] = 'DENY'
    headers['X-XSS-Protection'] = '1; mode=block'
xyb's avatar
xyb committed
241
    headers['X-UA-Compatible'] = 'IE=edge'
242
    headers['X-Content-Type-Options'] = 'nosniff'
243 244 245 246 247 248 249

    if current_user
      # Adds `no-store` to the DEFAULT_CACHE_CONTROL, to prevent security
      # concerns due to caching private data.
      headers['Cache-Control'] = DEFAULT_GITLAB_CACHE_CONTROL
      headers["Pragma"] = "no-cache" # HTTP 1.0 compatibility
    end
250
  end
251

tduehr's avatar
tduehr committed
252 253 254 255
  def validate_user_service_ticket!
    return unless signed_in? && session[:service_tickets]

    valid = session[:service_tickets].all? do |provider, ticket|
256
      Gitlab::Auth::OAuth::Session.valid?(provider, ticket)
tduehr's avatar
tduehr committed
257 258 259 260 261 262 263 264 265
    end

    unless valid
      session[:service_tickets] = nil
      sign_out current_user
      redirect_to new_user_session_path
    end
  end

266
  def check_password_expiration
267
    return if session[:impersonator_id] || !current_user&.allow_password_authentication?
268 269 270 271

    password_expires_at = current_user&.password_expires_at

    if password_expires_at && password_expires_at < Time.now
Douwe Maan's avatar
Douwe Maan committed
272
      return redirect_to new_profile_password_path
273 274
    end
  end
275

276
  def ldap_security_check
277
    if current_user && current_user.requires_ldap_check?
Jacob Vosmaer's avatar
Jacob Vosmaer committed
278
      return unless current_user.try_obtain_ldap_lease
279

280
      unless Gitlab::Auth::LDAP::Access.allowed?(current_user)
281 282 283
        sign_out current_user
        flash[:alert] = "Access denied for your LDAP account."
        redirect_to new_user_session_path
284 285 286 287
      end
    end
  end

288
  def event_filter
289 290 291 292
    @event_filter ||=
      EventFilter.new(params[:event_filter].presence || cookies[:event_filter]).tap do |new_event_filter|
        cookies[:event_filter] = new_event_filter.filter
      end
293
  end
294 295

  # JSON for infinite scroll via Pager object
296
  def pager_json(partial, count, locals = {})
297 298
    html = render_to_string(
      partial,
299
      locals: locals,
300 301 302 303 304 305 306 307 308
      layout: false,
      formats: [:html]
    )

    render json: {
      html: html,
      count: count
    }
  end
309

Josh Frye's avatar
Josh Frye committed
310
  def view_to_html_string(partial, locals = {})
311
    render_to_string(
Josh Frye's avatar
Josh Frye committed
312
      partial,
313
      locals: locals,
314 315 316 317
      layout: false,
      formats: [:html]
    )
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
318 319

  def configure_permitted_parameters
320
    devise_parameter_sanitizer.permit(:sign_in, keys: [:username, :email, :password, :login, :remember_me, :otp_attempt])
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
321
  end
322 323 324 325

  def hexdigest(string)
    Digest::SHA1.hexdigest string
  end
326 327

  def require_email
328
    if current_user && current_user.temp_oauth_email? && session[:impersonator_id].nil?
Douwe Maan's avatar
Douwe Maan committed
329
      return redirect_to profile_path, notice: 'Please complete your profile with email address'
330 331
    end
  end
332

333 334 335 336
  def enforce_terms!
    return unless current_user
    return if current_user.terms_accepted?

337 338
    message = _("Please accept the Terms of Service before continuing.")

339
    if sessionless_user?
340
      access_denied!(message)
341 342 343 344 345 346 347 348 349 350
    else
      # Redirect to the destination if the request is a get.
      # Redirect to the source if it was a post, so the user can re-submit after
      # accepting the terms.
      redirect_path = if request.get?
                        request.fullpath
                      else
                        URI(request.referer).path if request.referer
                      end

351
      flash[:notice] = message
352 353 354 355
      redirect_to terms_path(redirect: redirect_path), status: :found
    end
  end

356
  def import_sources_enabled?
357
    !Gitlab::CurrentSettings.import_sources.empty?
358 359
  end

360 361 362 363
  def bitbucket_server_import_enabled?
    Gitlab::CurrentSettings.import_sources.include?('bitbucket_server')
  end

364
  def github_import_enabled?
365
    Gitlab::CurrentSettings.import_sources.include?('github')
366 367
  end

368
  def gitea_import_enabled?
369
    Gitlab::CurrentSettings.import_sources.include?('gitea')
Kim "BKC" Carlbäcker's avatar
Kim "BKC" Carlbäcker committed
370 371
  end

372
  def github_import_configured?
373
    Gitlab::Auth::OAuth::Provider.enabled?(:github)
374 375 376
  end

  def gitlab_import_enabled?
377
    request.host != 'gitlab.com' && Gitlab::CurrentSettings.import_sources.include?('gitlab')
378 379 380
  end

  def gitlab_import_configured?
381
    Gitlab::Auth::OAuth::Provider.enabled?(:gitlab)
382 383 384
  end

  def bitbucket_import_enabled?
385
    Gitlab::CurrentSettings.import_sources.include?('bitbucket')
386 387 388
  end

  def bitbucket_import_configured?
389
    Gitlab::Auth::OAuth::Provider.enabled?(:bitbucket)
390
  end
391 392

  def google_code_import_enabled?
393
    Gitlab::CurrentSettings.import_sources.include?('google_code')
394 395
  end

Jared Szechy's avatar
Jared Szechy committed
396
  def fogbugz_import_enabled?
397
    Gitlab::CurrentSettings.import_sources.include?('fogbugz')
Jared Szechy's avatar
Jared Szechy committed
398 399
  end

400
  def git_import_enabled?
401
    Gitlab::CurrentSettings.import_sources.include?('git')
402
  end
403

404
  def gitlab_project_import_enabled?
405
    Gitlab::CurrentSettings.import_sources.include?('gitlab_project')
406 407
  end

408
  def manifest_import_enabled?
409
    Group.supports_nested_groups? && Gitlab::CurrentSettings.import_sources.include?('manifest')
410 411
  end

412 413 414 415 416 417
  # U2F (universal 2nd factor) devices need a unique identifier for the application
  # to perform authentication.
  # https://developers.yubico.com/U2F/App_ID.html
  def u2f_app_id
    request.base_url
  end
418

419 420
  def set_locale(&block)
    Gitlab::I18n.with_user_locale(current_user, &block)
421
  end
422

423
  def set_page_title_header
424
    # Per https://tools.ietf.org/html/rfc5987, headers need to be ISO-8859-1, not UTF-8
425
    response.headers['Page-Title'] = URI.escape(page_title('GitLab'))
426
  end
427 428 429 430

  def peek_request?
    request.path.start_with?('/-/peek')
  end
431

432 433 434 435
  def json_request?
    request.format.json?
  end

436 437 438 439 440
  def should_enforce_terms?
    return false unless Gitlab::CurrentSettings.current_application_settings.enforce_terms

    !(peek_request? || devise_controller?)
  end
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

  def set_usage_stats_consent_flag
    return unless current_user
    return if sessionless_user?
    return if session.has_key?(:ask_for_usage_stats_consent)

    session[:ask_for_usage_stats_consent] = current_user.requires_usage_stats_consent?

    if session[:ask_for_usage_stats_consent]
      disable_usage_stats
    end
  end

  def disable_usage_stats
    application_setting_params = {
      usage_ping_enabled: false,
      version_check_enabled: false,
      skip_usage_stats_user: true
    }
    settings = Gitlab::CurrentSettings.current_application_settings

    ApplicationSettings::UpdateService
      .new(settings, current_user, application_setting_params)
      .execute
  end
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

  def check_impersonation_availability
    return unless session[:impersonator_id]

    unless Gitlab.config.gitlab.impersonation_enabled
      stop_impersonation
      access_denied! _('Impersonation has been disabled')
    end
  end

  def stop_impersonation
    impersonated_user = current_user

    Gitlab::AppLogger.info("User #{impersonator.username} has stopped impersonating #{impersonated_user.username}")

    warden.set_user(impersonator, scope: :user)
    session[:impersonator_id] = nil

    impersonated_user
  end

  def impersonator
    @impersonator ||= User.find(session[:impersonator_id]) if session[:impersonator_id]
  end
490 491 492 493

  def sentry_context
    Gitlab::Sentry.context(current_user)
  end
gitlabhq's avatar
gitlabhq committed
494
end