application_controller.rb 15.3 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
  before_action :authenticate_user!
17
  before_action :enforce_terms!, if: :should_enforce_terms?
tduehr's avatar
tduehr committed
18
  before_action :validate_user_service_ticket!
19 20
  before_action :check_password_expiration
  before_action :ldap_security_check
21
  before_action :sentry_context
22
  before_action :default_headers
23
  before_action :add_gon_variables, unless: [:peek_request?, :json_request?]
24 25
  before_action :configure_permitted_parameters, if: :devise_controller?
  before_action :require_email, unless: :devise_controller?
26
  before_action :set_usage_stats_consent_flag
27
  before_action :check_impersonation_availability
28

29
  around_action :set_locale
30
  around_action :set_session_storage
31

32
  after_action :set_page_title_header, if: :json_request?
33
  after_action :limit_unauthenticated_session_times
34

35
  protect_from_forgery with: :exception, prepend: true
36

37
  helper_method :can?
38 39 40 41
  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?,
42
    :bitbucket_server_import_enabled?,
43 44
    :google_code_import_enabled?, :fogbugz_import_enabled?,
    :git_import_enabled?, :gitlab_project_import_enabled?,
Bob Van Landuyt's avatar
Bob Van Landuyt committed
45
    :manifest_import_enabled?, :phabricator_import_enabled?
gitlabhq's avatar
gitlabhq committed
46

47 48
  # Adds `no-store` to the DEFAULT_CACHE_CONTROL, to prevent security
  # concerns due to caching private data.
49
  DEFAULT_GITLAB_CACHE_CONTROL = "#{ActionDispatch::Http::Cache::Response::DEFAULT_CACHE_CONTROL}, no-store".freeze
50
  DEFAULT_GITLAB_CONTROL_NO_CACHE = "#{DEFAULT_GITLAB_CACHE_CONTROL}, no-cache".freeze
51

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

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

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

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

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

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

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

    render_503
  end

82
  def redirect_back_or_default(default: root_path, options: {})
83
    redirect_back(fallback_location: default, **options)
84 85
  end

86 87 88 89
  def not_found
    render_404
  end

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

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  # 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

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

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

127 128 129 130
  def workhorse_excluded_content_types
    @workhorse_excluded_content_types ||= %w(text/html application/json)
  end

131 132
  def append_info_to_payload(payload)
    super
133

134
    payload[:ua] = request.env["HTTP_USER_AGENT"]
135
    payload[:remote_ip] = request.remote_ip
136
    payload[Labkit::Correlation::CorrelationId::LOG_KEY] = Labkit::Correlation::CorrelationId.current_id
137

138 139 140 141 142
    logged_user = auth_user

    if logged_user.present?
      payload[:user_id] = logged_user.try(:id)
      payload[:username] = logged_user.try(:username)
143
    end
144 145 146 147

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

    payload[:queue_duration] = request.env[::Gitlab::Middleware::RailsQueueDuration::GITLAB_RAILS_QUEUE_DURATION_KEY]
150 151
  end

152
  ##
153
  # Controllers such as GitHttpController may use alternative methods
154 155
  # (e.g. tokens) to authenticate the user, whereas Devise sets current_user.
  #
156
  def auth_user
157
    if user_signed_in?
158 159 160 161
      current_user
    else
      try(:authenticated_user)
    end
162 163
  end

Riyad Preukschas's avatar
Riyad Preukschas committed
164
  def log_exception(exception)
165
    Gitlab::Sentry.track_acceptable_exception(exception)
Stan Hu's avatar
Stan Hu committed
166

Jasper Maes's avatar
Jasper Maes committed
167
    backtrace_cleaner = request.env["action_dispatch.backtrace_cleaner"]
168
    application_trace = ActionDispatch::ExceptionWrapper.new(backtrace_cleaner, exception).application_trace
169
    application_trace.map! { |t| "  #{t}\n" }
Riyad Preukschas's avatar
Riyad Preukschas committed
170 171 172
    logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  end

173
  def after_sign_in_path_for(resource)
174
    stored_location_for(:redirect) || stored_location_for(resource) || root_path
randx's avatar
randx committed
175 176
  end

177
  def after_sign_out_path_for(resource)
178
    Gitlab::CurrentSettings.after_sign_out_path.presence || new_user_session_path
179 180
  end

181
  def can?(object, action, subject = :global)
182
    Ability.allowed?(object, action, subject)
gitlabhq's avatar
gitlabhq committed
183 184
  end

185
  def access_denied!(message = nil, status = nil)
186 187 188
    # 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
189
    status ||= message.present? ? :forbidden : :not_found
190 191 192 193 194 195
    template =
      if status == :not_found
        "errors/not_found"
      else
        "errors/access_denied"
      end
196

Fatih Acet's avatar
Fatih Acet committed
197
    respond_to do |format|
198
      format.any { head status }
199
      format.html do
200
        render template,
201
               layout: "errors",
202
               status: status,
203 204
               locals: { message: message }
      end
Fatih Acet's avatar
Fatih Acet committed
205
    end
206 207 208
  end

  def git_not_found!
209
    render "errors/git_not_found.html", layout: "errors", status: 404
gitlabhq's avatar
gitlabhq committed
210 211
  end

212
  def render_403
Paul Slaughter's avatar
Paul Slaughter committed
213 214 215 216
    respond_to do |format|
      format.any { head :forbidden }
      format.html { render "errors/access_denied", layout: "errors", status: 403 }
    end
gitlabhq's avatar
gitlabhq committed
217
  end
gitlabhq's avatar
gitlabhq committed
218

219
  def render_404
220
    respond_to do |format|
Paul Slaughter's avatar
Paul Slaughter committed
221
      format.html { render "errors/not_found", layout: "errors", status: 404 }
222 223
      # 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
224
      format.any { head :not_found }
225
    end
226 227
  end

228 229 230 231
  def respond_422
    head :unprocessable_entity
  end

232 233 234 235 236 237 238 239 240 241 242 243 244
  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

245
  def no_cache_headers
246 247 248
    headers['Cache-Control'] = DEFAULT_GITLAB_CONTROL_NO_CACHE
    headers['Pragma'] = 'no-cache' # HTTP 1.0 compatibility
    headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT'
249
  end
250

251 252 253
  def default_headers
    headers['X-Frame-Options'] = 'DENY'
    headers['X-XSS-Protection'] = '1; mode=block'
xyb's avatar
xyb committed
254
    headers['X-UA-Compatible'] = 'IE=edge'
255
    headers['X-Content-Type-Options'] = 'nosniff'
256 257

    if current_user
258 259 260 261 262 263 264 265 266 267
      headers['Cache-Control'] = default_cache_control
      headers['Pragma'] = 'no-cache' # HTTP 1.0 compatibility
    end
  end

  def default_cache_control
    if request.xhr?
      ActionDispatch::Http::Cache::Response::DEFAULT_CACHE_CONTROL
    else
      DEFAULT_GITLAB_CACHE_CONTROL
268
    end
269
  end
270

tduehr's avatar
tduehr committed
271 272 273 274
  def validate_user_service_ticket!
    return unless signed_in? && session[:service_tickets]

    valid = session[:service_tickets].all? do |provider, ticket|
275
      Gitlab::Auth::OAuth::Session.valid?(provider, ticket)
tduehr's avatar
tduehr committed
276 277 278 279 280 281 282 283 284
    end

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

285
  def check_password_expiration
286
    return if session[:impersonator_id] || !current_user&.allow_password_authentication?
287 288 289 290

    password_expires_at = current_user&.password_expires_at

    if password_expires_at && password_expires_at < Time.now
Douwe Maan's avatar
Douwe Maan committed
291
      return redirect_to new_profile_password_path
292 293
    end
  end
294

295
  def ldap_security_check
296
    if current_user && current_user.requires_ldap_check?
Jacob Vosmaer's avatar
Jacob Vosmaer committed
297
      return unless current_user.try_obtain_ldap_lease
298

299
      unless Gitlab::Auth::LDAP::Access.allowed?(current_user)
300
        sign_out current_user
301
        flash[:alert] = _("Access denied for your LDAP account.")
302
        redirect_to new_user_session_path
303 304 305 306
      end
    end
  end

307
  def event_filter
308 309 310 311
    @event_filter ||=
      EventFilter.new(params[:event_filter].presence || cookies[:event_filter]).tap do |new_event_filter|
        cookies[:event_filter] = new_event_filter.filter
      end
312
  end
313 314

  # JSON for infinite scroll via Pager object
315
  def pager_json(partial, count, locals = {})
316 317
    html = render_to_string(
      partial,
318
      locals: locals,
319 320 321 322 323 324 325 326 327
      layout: false,
      formats: [:html]
    )

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

Josh Frye's avatar
Josh Frye committed
329
  def view_to_html_string(partial, locals = {})
330
    render_to_string(
Josh Frye's avatar
Josh Frye committed
331
      partial,
332
      locals: locals,
333 334 335 336
      layout: false,
      formats: [:html]
    )
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
337 338

  def configure_permitted_parameters
339
    devise_parameter_sanitizer.permit(:sign_in, keys: [:username, :email, :password, :login, :remember_me, :otp_attempt])
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
340
  end
341 342 343 344

  def hexdigest(string)
    Digest::SHA1.hexdigest string
  end
345 346

  def require_email
347
    if current_user && current_user.temp_oauth_email? && session[:impersonator_id].nil?
348
      return redirect_to profile_path, notice: _('Please complete your profile with email address')
349 350
    end
  end
351

352 353 354 355
  def enforce_terms!
    return unless current_user
    return if current_user.terms_accepted?

356 357
    message = _("Please accept the Terms of Service before continuing.")

358
    if sessionless_user?
359
      access_denied!(message)
360 361 362 363 364 365 366 367 368 369
    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

370
      flash[:notice] = message
371 372 373 374
      redirect_to terms_path(redirect: redirect_path), status: :found
    end
  end

375
  def import_sources_enabled?
376
    !Gitlab::CurrentSettings.import_sources.empty?
377 378
  end

379 380 381 382
  def bitbucket_server_import_enabled?
    Gitlab::CurrentSettings.import_sources.include?('bitbucket_server')
  end

383
  def github_import_enabled?
384
    Gitlab::CurrentSettings.import_sources.include?('github')
385 386
  end

387
  def gitea_import_enabled?
388
    Gitlab::CurrentSettings.import_sources.include?('gitea')
Kim "BKC" Carlbäcker's avatar
Kim "BKC" Carlbäcker committed
389 390
  end

391
  def github_import_configured?
392
    Gitlab::Auth::OAuth::Provider.enabled?(:github)
393 394 395
  end

  def gitlab_import_enabled?
396
    request.host != 'gitlab.com' && Gitlab::CurrentSettings.import_sources.include?('gitlab')
397 398 399
  end

  def gitlab_import_configured?
400
    Gitlab::Auth::OAuth::Provider.enabled?(:gitlab)
401 402 403
  end

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

  def bitbucket_import_configured?
408
    Gitlab::Auth::OAuth::Provider.enabled?(:bitbucket)
409
  end
410 411

  def google_code_import_enabled?
412
    Gitlab::CurrentSettings.import_sources.include?('google_code')
413 414
  end

Jared Szechy's avatar
Jared Szechy committed
415
  def fogbugz_import_enabled?
416
    Gitlab::CurrentSettings.import_sources.include?('fogbugz')
Jared Szechy's avatar
Jared Szechy committed
417 418
  end

419
  def git_import_enabled?
420
    Gitlab::CurrentSettings.import_sources.include?('git')
421
  end
422

423
  def gitlab_project_import_enabled?
424
    Gitlab::CurrentSettings.import_sources.include?('gitlab_project')
425 426
  end

427
  def manifest_import_enabled?
428
    Gitlab::CurrentSettings.import_sources.include?('manifest')
429 430
  end

Bob Van Landuyt's avatar
Bob Van Landuyt committed
431 432 433 434
  def phabricator_import_enabled?
    Gitlab::PhabricatorImport.available?
  end

435 436 437 438 439 440
  # 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
441

442 443
  def set_locale(&block)
    Gitlab::I18n.with_user_locale(current_user, &block)
444
  end
445

446
  def set_session_storage(&block)
447 448
    return yield if sessionless_user?

449 450 451
    Gitlab::Session.with_session(session, &block)
  end

452
  def set_page_title_header
453
    # Per https://tools.ietf.org/html/rfc5987, headers need to be ISO-8859-1, not UTF-8
454
    response.headers['Page-Title'] = URI.escape(page_title('GitLab'))
455
  end
456 457 458 459

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

461 462 463 464
  def json_request?
    request.format.json?
  end

465 466 467 468 469
  def should_enforce_terms?
    return false unless Gitlab::CurrentSettings.current_application_settings.enforce_terms

    !(peek_request? || devise_controller?)
  end
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494

  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
495 496 497 498 499 500 501 502 503 504 505

  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
506
    log_impersonation_event
507 508 509 510 511 512 513

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

    impersonated_user
  end

514 515 516 517 518 519 520 521
  def impersonated_user
    current_user
  end

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

522 523 524
  def impersonator
    @impersonator ||= User.find(session[:impersonator_id]) if session[:impersonator_id]
  end
525 526 527 528

  def sentry_context
    Gitlab::Sentry.context(current_user)
  end
529 530 531 532 533 534

  def allow_gitaly_ref_name_caching
    ::Gitlab::GitalyClient.allow_ref_name_caching do
      yield
    end
  end
gitlabhq's avatar
gitlabhq committed
535
end