Handle negative offset param in `api/v2/search` (#28282)

th-new
Matt Jankowski 2023-12-19 05:55:39 -05:00 committed by GitHub
parent 7b1d390734
commit c28976d89e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 1 deletions

View File

@ -108,6 +108,10 @@ class Api::BaseController < ApplicationController
render json: { error: 'Your login is currently disabled' }, status: 403 if current_user&.account&.unavailable? render json: { error: 'Your login is currently disabled' }, status: 403 if current_user&.account&.unavailable?
end end
def require_valid_pagination_options!
render json: { error: 'Pagination values for `offset` and `limit` must be positive' }, status: 400 if pagination_options_invalid?
end
def require_user! def require_user!
if !current_user if !current_user
render json: { error: 'This method requires an authenticated user' }, status: 422 render json: { error: 'This method requires an authenticated user' }, status: 422
@ -136,6 +140,10 @@ class Api::BaseController < ApplicationController
private private
def pagination_options_invalid?
params.slice(:limit, :offset).values.map(&:to_i).any?(&:negative?)
end
def respond_with_error(code) def respond_with_error(code)
render json: { error: Rack::Utils::HTTP_STATUS_CODES[code] }, status: code render json: { error: Rack::Utils::HTTP_STATUS_CODES[code] }, status: code
end end

View File

@ -12,6 +12,7 @@ class Api::V2::SearchController < Api::BaseController
before_action :query_pagination_error, if: :pagination_requested? before_action :query_pagination_error, if: :pagination_requested?
before_action :remote_resolve_error, if: :remote_resolve_requested? before_action :remote_resolve_error, if: :remote_resolve_requested?
end end
before_action :require_valid_pagination_options!
def index def index
@search = Search.new(search_results) @search = Search.new(search_results)

View File

@ -40,7 +40,7 @@ describe 'Search API' do
end end
end end
context 'with `offset`' do context 'with valid `offset` value' do
let(:params) { { q: 'test1', offset: 1 } } let(:params) { { q: 'test1', offset: 1 } }
it 'returns http unauthorized' do it 'returns http unauthorized' do
@ -50,6 +50,26 @@ describe 'Search API' do
end end
end end
context 'with negative `offset` value' do
let(:params) { { q: 'test1', offset: '-100', type: 'accounts' } }
it 'returns http bad_request' do
get '/api/v2/search', headers: headers, params: params
expect(response).to have_http_status(400)
end
end
context 'with negative `limit` value' do
let(:params) { { q: 'test1', limit: '-100', type: 'accounts' } }
it 'returns http bad_request' do
get '/api/v2/search', headers: headers, params: params
expect(response).to have_http_status(400)
end
end
context 'with following=true' do context 'with following=true' do
let(:params) { { q: 'test', type: 'accounts', following: 'true' } } let(:params) { { q: 'test', type: 'accounts', following: 'true' } }