2019-08-22 06:57:44 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-07-26 06:34:52 -04:00
|
|
|
require 'spec_helper'
|
|
|
|
|
2020-06-24 14:09:03 -04:00
|
|
|
RSpec.describe Gitlab::RequestForgeryProtection, :allow_forgery_protection do
|
2017-07-26 06:34:52 -04:00
|
|
|
let(:csrf_token) { SecureRandom.base64(ActionController::RequestForgeryProtection::AUTHENTICITY_TOKEN_LENGTH) }
|
|
|
|
let(:env) do
|
|
|
|
{
|
|
|
|
'rack.input' => '',
|
|
|
|
'rack.session' => {
|
|
|
|
_csrf_token: csrf_token
|
|
|
|
}
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
describe '.call' do
|
|
|
|
context 'when the request method is GET' do
|
|
|
|
before do
|
|
|
|
env['REQUEST_METHOD'] = 'GET'
|
|
|
|
end
|
|
|
|
|
|
|
|
it 'does not raise an exception' do
|
|
|
|
expect { described_class.call(env) }.not_to raise_exception
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
context 'when the request method is POST' do
|
|
|
|
before do
|
|
|
|
env['REQUEST_METHOD'] = 'POST'
|
|
|
|
end
|
|
|
|
|
|
|
|
context 'when the CSRF token is valid' do
|
|
|
|
before do
|
|
|
|
env['HTTP_X_CSRF_TOKEN'] = csrf_token
|
|
|
|
end
|
|
|
|
|
|
|
|
it 'does not raise an exception' do
|
|
|
|
expect { described_class.call(env) }.not_to raise_exception
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
context 'when the CSRF token is invalid' do
|
|
|
|
before do
|
|
|
|
env['HTTP_X_CSRF_TOKEN'] = 'foo'
|
|
|
|
end
|
|
|
|
|
|
|
|
it 'raises an ActionController::InvalidAuthenticityToken exception' do
|
|
|
|
expect { described_class.call(env) }.to raise_exception(ActionController::InvalidAuthenticityToken)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
describe '.verified?' do
|
2021-02-10 13:09:02 -05:00
|
|
|
it 'does not modify the env' do
|
|
|
|
env['REQUEST_METHOD'] = "GET"
|
|
|
|
expect { described_class.verified?(env) }.not_to change { env }
|
|
|
|
end
|
|
|
|
|
2017-07-26 06:34:52 -04:00
|
|
|
context 'when the request method is GET' do
|
|
|
|
before do
|
|
|
|
env['REQUEST_METHOD'] = 'GET'
|
|
|
|
end
|
|
|
|
|
|
|
|
it 'returns true' do
|
|
|
|
expect(described_class.verified?(env)).to be_truthy
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
context 'when the request method is POST' do
|
|
|
|
before do
|
|
|
|
env['REQUEST_METHOD'] = 'POST'
|
|
|
|
end
|
|
|
|
|
|
|
|
context 'when the CSRF token is valid' do
|
|
|
|
before do
|
|
|
|
env['HTTP_X_CSRF_TOKEN'] = csrf_token
|
|
|
|
end
|
|
|
|
|
|
|
|
it 'returns true' do
|
|
|
|
expect(described_class.verified?(env)).to be_truthy
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
context 'when the CSRF token is invalid' do
|
|
|
|
before do
|
|
|
|
env['HTTP_X_CSRF_TOKEN'] = 'foo'
|
|
|
|
end
|
|
|
|
|
|
|
|
it 'returns false' do
|
|
|
|
expect(described_class.verified?(env)).to be_falsey
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|