application_controller_spec.rb 20.8 KB
Newer Older
1
# coding: utf-8
2 3 4
require 'spec_helper'

describe ApplicationController do
5 6
  include TermsHelper

7 8
  let(:user) { create(:user) }

9
  describe '#check_password_expiration' do
10
    let(:controller) { described_class.new }
11

12 13 14 15
    before do
      allow(controller).to receive(:session).and_return({})
    end

16
    it 'redirects if the user is over their password expiry' do
17
      user.password_expires_at = Time.new(2002)
18

19 20 21 22
      expect(user.ldap_user?).to be_falsey
      allow(controller).to receive(:current_user).and_return(user)
      expect(controller).to receive(:redirect_to)
      expect(controller).to receive(:new_profile_password_path)
23

24 25 26
      controller.send(:check_password_expiration)
    end

27
    it 'does not redirect if the user is under their password expiry' do
28
      user.password_expires_at = Time.now + 20010101
29

30 31 32
      expect(user.ldap_user?).to be_falsey
      allow(controller).to receive(:current_user).and_return(user)
      expect(controller).not_to receive(:redirect_to)
33

34 35 36
      controller.send(:check_password_expiration)
    end

37
    it 'does not redirect if the user is over their password expiry but they are an ldap user' do
38
      user.password_expires_at = Time.new(2002)
39

40 41 42
      allow(user).to receive(:ldap_user?).and_return(true)
      allow(controller).to receive(:current_user).and_return(user)
      expect(controller).not_to receive(:redirect_to)
43

44 45
      controller.send(:check_password_expiration)
    end
46

47 48 49
    it 'does not redirect if the user is over their password expiry but password authentication is disabled for the web interface' do
      stub_application_setting(password_authentication_enabled_for_web: false)
      stub_application_setting(password_authentication_enabled_for_git: false)
50
      user.password_expires_at = Time.new(2002)
51

52
      allow(controller).to receive(:current_user).and_return(user)
53
      expect(controller).not_to receive(:redirect_to)
54 55 56

      controller.send(:check_password_expiration)
    end
57
  end
58

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  describe '#add_gon_variables' do
    before do
      Gon.clear
      sign_in user
    end

    let(:json_response) { JSON.parse(response.body) }

    controller(described_class) do
      def index
        render json: Gon.all_variables
      end
    end

    shared_examples 'setting gon variables' do
      it 'sets gon variables' do
        get :index, format: format

        expect(json_response.size).not_to be_zero
      end
    end

    shared_examples 'not setting gon variables' do
      it 'does not set gon variables' do
        get :index, format: format

        expect(json_response.size).to be_zero
      end
    end

    context 'with html format' do
      let(:format) { :html }

      it_behaves_like 'setting gon variables'

      context 'for peek requests' do
        before do
          request.path = '/-/peek'
        end

        it_behaves_like 'not setting gon variables'
      end
    end

    context 'with json format' do
      let(:format) { :json }

      it_behaves_like 'not setting gon variables'
    end
  end

110
  describe "#authenticate_user_from_personal_access_token!" do
111 112 113 114
    before do
      stub_authentication_activity_metrics(debug: false)
    end

115 116 117
    controller(described_class) do
      def index
        render text: 'authenticated'
118
      end
119 120
    end

121
    let(:personal_access_token) { create(:personal_access_token, user: user) }
122

123 124
    context "when the 'personal_access_token' param is populated with the personal access token" do
      it "logs the user in" do
125 126 127 128 129
        expect(authentication_metrics)
          .to increment(:user_authenticated_counter)
          .and increment(:user_session_override_counter)
          .and increment(:user_sessionless_authentication_counter)

130
        get :index, private_token: personal_access_token.token
131

132 133
        expect(response).to have_gitlab_http_status(200)
        expect(response.body).to eq('authenticated')
134
      end
135
    end
136

137 138
    context "when the 'PERSONAL_ACCESS_TOKEN' header is populated with the personal access token" do
      it "logs the user in" do
139 140 141 142 143
        expect(authentication_metrics)
          .to increment(:user_authenticated_counter)
          .and increment(:user_session_override_counter)
          .and increment(:user_sessionless_authentication_counter)

144 145
        @request.headers["PRIVATE-TOKEN"] = personal_access_token.token
        get :index
146

147 148
        expect(response).to have_gitlab_http_status(200)
        expect(response.body).to eq('authenticated')
149
      end
150
    end
151

152
    it "doesn't log the user in otherwise" do
153 154 155
      expect(authentication_metrics)
        .to increment(:user_unauthenticated_counter)

156
      get :index, private_token: "token"
157

158 159
      expect(response.status).not_to eq(200)
      expect(response.body).not_to eq('authenticated')
160 161
    end
  end
162

163 164
  describe 'session expiration' do
    controller(described_class) do
165 166 167 168
      # The anonymous controller will report 401 and fail to run any actions.
      # Normally, GitLab will just redirect you to sign in.
      skip_before_action :authenticate_user!, only: :index

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
      def index
        render text: 'authenticated'
      end
    end

    context 'authenticated user' do
      it 'does not set the expire_after option' do
        sign_in(create(:user))

        get :index

        expect(request.env['rack.session.options'][:expire_after]).to be_nil
      end
    end

    context 'unauthenticated user' do
      it 'sets the expire_after option' do
        get :index

        expect(request.env['rack.session.options'][:expire_after]).to eq(Settings.gitlab['unauthenticated_session_expire_delay'])
      end
    end
  end

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
  describe 'rescue from Gitlab::Git::Storage::Inaccessible' do
    controller(described_class) do
      def index
        raise Gitlab::Git::Storage::Inaccessible.new('broken', 100)
      end
    end

    it 'renders a 503 when storage is not available' do
      sign_in(create(:user))

      get :index

      expect(response.status).to eq(503)
    end

    it 'renders includes a Retry-After header' do
      sign_in(create(:user))

      get :index

      expect(response.headers['Retry-After']).to eq(100)
    end
  end

217 218 219 220 221 222 223 224 225 226 227
  describe 'response format' do
    controller(described_class) do
      def index
        respond_to do |format|
          format.json do
            head :ok
          end
        end
      end
    end

228 229 230 231
    before do
      sign_in user
    end

232 233 234 235
    context 'when format is handled' do
      let(:requested_format) { :json }

      it 'returns 200 response' do
236
        get :index, format: requested_format
237

238
        expect(response).to have_gitlab_http_status 200
239 240 241 242 243
      end
    end

    context 'when format is not handled' do
      it 'returns 404 response' do
244
        get :index
245

246
        expect(response).to have_gitlab_http_status 404
247 248 249 250
      end
    end
  end

251
  describe '#authenticate_sessionless_user!' do
252 253 254 255
    before do
      stub_authentication_activity_metrics(debug: false)
    end

256
    describe 'authenticating a user from a feed token' do
257 258 259 260 261 262
      controller(described_class) do
        def index
          render text: 'authenticated'
        end
      end

263
      context "when the 'feed_token' param is populated with the feed token" do
264 265
        context 'when the request format is atom' do
          it "logs the user in" do
266 267 268 269 270
            expect(authentication_metrics)
              .to increment(:user_authenticated_counter)
              .and increment(:user_session_override_counter)
              .and increment(:user_sessionless_authentication_counter)

271
            get :index, feed_token: user.feed_token, format: :atom
272

273
            expect(response).to have_gitlab_http_status 200
274 275 276 277
            expect(response.body).to eq 'authenticated'
          end
        end

278 279
        context 'when the request format is ics' do
          it "logs the user in" do
280 281 282 283 284
            expect(authentication_metrics)
              .to increment(:user_authenticated_counter)
              .and increment(:user_session_override_counter)
              .and increment(:user_sessionless_authentication_counter)

285
            get :index, feed_token: user.feed_token, format: :ics
286

287 288 289 290 291 292
            expect(response).to have_gitlab_http_status 200
            expect(response.body).to eq 'authenticated'
          end
        end

        context 'when the request format is neither atom nor ics' do
293
          it "doesn't log the user in" do
294 295 296
            expect(authentication_metrics)
              .to increment(:user_unauthenticated_counter)

297
            get :index, feed_token: user.feed_token
298

299
            expect(response.status).not_to have_gitlab_http_status 200
300 301 302 303 304
            expect(response.body).not_to eq 'authenticated'
          end
        end
      end

305
      context "when the 'feed_token' param is populated with an invalid feed token" do
306
        it "doesn't log the user" do
307 308 309
          expect(authentication_metrics)
            .to increment(:user_unauthenticated_counter)

310
          get :index, feed_token: 'token', format: :atom
311

312 313 314 315 316 317 318
          expect(response.status).not_to eq 200
          expect(response.body).not_to eq 'authenticated'
        end
      end
    end
  end

319 320 321 322 323 324 325
  describe '#route_not_found' do
    it 'renders 404 if authenticated' do
      allow(controller).to receive(:current_user).and_return(user)
      expect(controller).to receive(:not_found)
      controller.send(:route_not_found)
    end

326
    it 'does redirect to login page via authenticate_user! if not authenticated' do
327
      allow(controller).to receive(:current_user).and_return(nil)
328
      expect(controller).to receive(:authenticate_user!)
329 330 331
      controller.send(:route_not_found)
    end
  end
332

333 334 335 336 337 338 339 340 341 342 343 344 345 346
  describe '#set_page_title_header' do
    let(:controller) { described_class.new }

    it 'URI encodes UTF-8 characters in the title' do
      response = double(headers: {})
      allow_any_instance_of(PageLayoutHelper).to receive(:page_title).and_return('€100 · GitLab')
      allow(controller).to receive(:response).and_return(response)

      controller.send(:set_page_title_header)

      expect(response.headers['Page-Title']).to eq('%E2%82%AC100%20%C2%B7%20GitLab')
    end
  end

347
  context 'two-factor authentication' do
348
    let(:controller) { described_class.new }
349

350 351
    describe '#check_two_factor_requirement' do
      subject { controller.send :check_two_factor_requirement }
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

      it 'does not redirect if 2FA is not required' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(false)
        expect(controller).not_to receive(:redirect_to)

        subject
      end

      it 'does not redirect if user is not logged in' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(true)
        allow(controller).to receive(:current_user).and_return(nil)
        expect(controller).not_to receive(:redirect_to)

        subject
      end

      it 'does not redirect if user has 2FA enabled' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(true)
        allow(controller).to receive(:current_user).twice.and_return(user)
        allow(user).to receive(:two_factor_enabled?).and_return(true)
        expect(controller).not_to receive(:redirect_to)

        subject
      end

      it 'does not redirect if 2FA setup can be skipped' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(true)
        allow(controller).to receive(:current_user).twice.and_return(user)
        allow(user).to receive(:two_factor_enabled?).and_return(false)
        allow(controller).to receive(:skip_two_factor?).and_return(true)
        expect(controller).not_to receive(:redirect_to)

        subject
      end

      it 'redirects to 2FA setup otherwise' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(true)
        allow(controller).to receive(:current_user).twice.and_return(user)
        allow(user).to receive(:two_factor_enabled?).and_return(false)
        allow(controller).to receive(:skip_two_factor?).and_return(false)
        allow(controller).to receive(:profile_two_factor_auth_path)
        expect(controller).to receive(:redirect_to)

        subject
      end
    end

    describe '#two_factor_authentication_required?' do
      subject { controller.send :two_factor_authentication_required? }

      it 'returns false if no 2FA requirement is present' do
        allow(controller).to receive(:current_user).and_return(nil)

        expect(subject).to be_falsey
      end

      it 'returns true if a 2FA requirement is set in the application settings' do
        stub_application_setting require_two_factor_authentication: true
        allow(controller).to receive(:current_user).and_return(nil)

        expect(subject).to be_truthy
      end

      it 'returns true if a 2FA requirement is set on the user' do
416
        user.require_two_factor_authentication_from_group = true
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
        allow(controller).to receive(:current_user).and_return(user)

        expect(subject).to be_truthy
      end
    end

    describe '#two_factor_grace_period' do
      subject { controller.send :two_factor_grace_period }

      it 'returns the grace period from the application settings' do
        stub_application_setting two_factor_grace_period: 23
        allow(controller).to receive(:current_user).and_return(nil)

        expect(subject).to eq 23
      end

      context 'with a 2FA requirement set on the user' do
434
        let(:user) { create :user, require_two_factor_authentication_from_group: true, two_factor_grace_period: 23 }
435 436 437 438 439 440 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 466 467 468 469 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 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

        it 'returns the user grace period if lower than the application grace period' do
          stub_application_setting two_factor_grace_period: 24
          allow(controller).to receive(:current_user).and_return(user)

          expect(subject).to eq 23
        end

        it 'returns the application grace period if lower than the user grace period' do
          stub_application_setting two_factor_grace_period: 22
          allow(controller).to receive(:current_user).and_return(user)

          expect(subject).to eq 22
        end
      end
    end

    describe '#two_factor_grace_period_expired?' do
      subject { controller.send :two_factor_grace_period_expired? }

      before do
        allow(controller).to receive(:current_user).and_return(user)
      end

      it 'returns false if the user has not started their grace period yet' do
        expect(subject).to be_falsey
      end

      context 'with grace period started' do
        let(:user) { create :user, otp_grace_period_started_at: 2.hours.ago }

        it 'returns true if the grace period has expired' do
          allow(controller).to receive(:two_factor_grace_period).and_return(1)

          expect(subject).to be_truthy
        end

        it 'returns false if the grace period is still active' do
          allow(controller).to receive(:two_factor_grace_period).and_return(3)

          expect(subject).to be_falsey
        end
      end
    end

    describe '#two_factor_skippable' do
      subject { controller.send :two_factor_skippable? }

      before do
        allow(controller).to receive(:current_user).and_return(user)
      end

      it 'returns false if 2FA is not required' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(false)

        expect(subject).to be_falsey
      end

      it 'returns false if the user has already enabled 2FA' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(true)
        allow(user).to receive(:two_factor_enabled?).and_return(true)

        expect(subject).to be_falsey
      end

      it 'returns false if the 2FA grace period has expired' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(true)
        allow(user).to receive(:two_factor_enabled?).and_return(false)
        allow(controller).to receive(:two_factor_grace_period_expired?).and_return(true)

        expect(subject).to be_falsey
      end

      it 'returns true otherwise' do
        allow(controller).to receive(:two_factor_authentication_required?).and_return(true)
        allow(user).to receive(:two_factor_enabled?).and_return(false)
        allow(controller).to receive(:two_factor_grace_period_expired?).and_return(false)

        expect(subject).to be_truthy
      end
    end

    describe '#skip_two_factor?' do
      subject { controller.send :skip_two_factor? }

      it 'returns false if 2FA setup was not skipped' do
        allow(controller).to receive(:session).and_return({})

        expect(subject).to be_falsey
      end

      context 'with 2FA setup skipped' do
        before do
528
          allow(controller).to receive(:session).and_return({ skip_two_factor: 2.hours.from_now })
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        end

        it 'returns false if the grace period has expired' do
          Timecop.freeze(3.hours.from_now) do
            expect(subject).to be_falsey
          end
        end

        it 'returns true if the grace period is still active' do
          Timecop.freeze(1.hour.from_now) do
            expect(subject).to be_truthy
          end
        end
      end
    end
  end
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

  context 'terms' do
    controller(described_class) do
      def index
        render text: 'authenticated'
      end
    end

    before do
      stub_env('IN_MEMORY_APPLICATION_SETTINGS', 'false')
      sign_in user
    end

    it 'does not query more when terms are enforced' do
      control = ActiveRecord::QueryRecorder.new { get :index }

      enforce_terms

      expect { get :index }.not_to exceed_query_limit(control)
    end

    context 'when terms are enforced' do
      before do
        enforce_terms
      end

      it 'redirects if the user did not accept the terms'  do
        get :index

        expect(response).to have_gitlab_http_status(302)
      end

      it 'does not redirect when the user accepted terms' do
        accept_terms(user)

        get :index

        expect(response).to have_gitlab_http_status(200)
      end

      context 'for sessionless users' do
586 587
        render_views

588 589 590 591 592
        before do
          sign_out user
        end

        it 'renders a 403 when the sessionless user did not accept the terms' do
593
          get :index, feed_token: user.feed_token, format: :atom
594 595 596 597

          expect(response).to have_gitlab_http_status(403)
        end

598 599 600 601 602 603 604 605
        it 'renders the error message when the format was html' do
          get :index,
              private_token: create(:personal_access_token, user: user).token,
              format: :html

          expect(response.body).to have_content /accept the terms of service/i
        end

606 607 608
        it 'renders a 200 when the sessionless user accepted the terms' do
          accept_terms(user)

609
          get :index, feed_token: user.feed_token, format: :atom
610 611 612 613 614 615

          expect(response).to have_gitlab_http_status(200)
        end
      end
    end
  end
616

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
  describe '#append_info_to_payload' do
    controller(described_class) do
      attr_reader :last_payload

      def index
        render text: 'authenticated'
      end

      def append_info_to_payload(payload)
        super

        @last_payload = payload
      end
    end

    it 'does not log errors with a 200 response' do
      get :index

      expect(controller.last_payload.has_key?(:response)).to be_falsey
    end

    context '422 errors' do
      it 'logs a response with a string' do
640
        response = spy(ActionDispatch::Response, status: 422, body: 'Hello world', content_type: 'application/json', cookies: {})
641 642 643 644 645 646 647 648
        allow(controller).to receive(:response).and_return(response)
        get :index

        expect(controller.last_payload[:response]).to eq('Hello world')
      end

      it 'logs a response with an array' do
        body = ['I want', 'my hat back']
649
        response = spy(ActionDispatch::Response, status: 422, body: body, content_type: 'application/json', cookies: {})
650 651 652 653 654 655 656
        allow(controller).to receive(:response).and_return(response)
        get :index

        expect(controller.last_payload[:response]).to eq(body)
      end

      it 'does not log a string with an empty body' do
657
        response = spy(ActionDispatch::Response, status: 422, body: nil, content_type: 'application/json', cookies: {})
658 659 660 661 662 663 664
        allow(controller).to receive(:response).and_return(response)
        get :index

        expect(controller.last_payload.has_key?(:response)).to be_falsey
      end

      it 'does not log an HTML body' do
665
        response = spy(ActionDispatch::Response, status: 422, body: 'This is a test', content_type: 'application/html', cookies: {})
666 667 668 669 670 671 672 673
        allow(controller).to receive(:response).and_return(response)
        get :index

        expect(controller.last_payload.has_key?(:response)).to be_falsey
      end
    end
  end

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
  describe '#access_denied' do
    controller(described_class) do
      def index
        access_denied!(params[:message])
      end
    end

    before do
      sign_in user
    end

    it 'renders a 404 without a message' do
      get :index

      expect(response).to have_gitlab_http_status(404)
    end

    it 'renders a 403 when a message is passed to access denied' do
      get :index, message: 'None shall pass'

      expect(response).to have_gitlab_http_status(403)
    end
  end
697
end