diff --git a/lib/noosfero/api/helpers.rb b/lib/noosfero/api/helpers.rb index 89bcd4c..2baa928 100644 --- a/lib/noosfero/api/helpers.rb +++ b/lib/noosfero/api/helpers.rb @@ -160,8 +160,21 @@ require 'grape' conditions end - def make_order_with_parameters(params) - params[:order] || "created_at DESC" + # changing make_order_with_parameters to avoid sql injection + def make_order_with_parameters(object, method, params) + order = "created_at DESC" + unless params[:order].blank? + field_name, direction = params[:order].split(' ') + assoc = object.class.reflect_on_association(method.to_sym) + if !field_name.blank? and assoc + if assoc.klass.attribute_names.include? field_name + if direction.present? and ['ASC','DESC'].include? direction.upcase + order = "#{field_name} #{direction.upcase}" + end + end + end + end + return order end def by_reference(scope, params) @@ -176,7 +189,7 @@ require 'grape' def select_filtered_collection_of(object, method, params) conditions = make_conditions_with_parameter(params) - order = make_order_with_parameters(params) + order = make_order_with_parameters(object,method,params) objects = object.send(method) objects = by_reference(objects, params) diff --git a/test/unit/api/helpers_test.rb b/test/unit/api/helpers_test.rb index 7d9e789..a567ce9 100644 --- a/test/unit/api/helpers_test.rb +++ b/test/unit/api/helpers_test.rb @@ -161,6 +161,27 @@ class APIHelpersTest < ActiveSupport::TestCase assert_nil make_conditions_with_parameter[:type] end + #test_should_make_order_with_parameters_return_order_if attribute_is_found_at_object_association + should 'make_order_with_parameters return order if attribute is found at object association' do + environment = Environment.new + params = {:order => "name ASC"} + assert_equal "name ASC", make_order_with_parameters(environment, "articles", params) + end + + # test added to check for eventual sql injection vunerabillity + #test_should_make_order_with_parameters_return_default_order_if_attributes_not_exists + should 'make_order_with_parameters return default order if attributes not exists' do + environment = Environment.new + params = {:order => "CRAZY_FIELD ASC"} # quote used to check sql injection vunerabillity + assert_equal "created_at DESC", make_order_with_parameters(environment, "articles", params) + end + + should 'make_order_with_parameters return default order if sql injection detected' do + environment = Environment.new + params = {:order => "name' ASC"} # quote used to check sql injection vunerabillity + assert_equal "created_at DESC", make_order_with_parameters(environment, "articles", params) + end + should 'render not_found if endpoint is unavailable' do Noosfero::API::API.stubs(:endpoint_unavailable?).returns(true) -- libgit2 0.21.2