2016-11-25 98 views
0

我试图从SQL注入保护自己,我在#WHERE使用变量作为列名:Rspec的不捕错误StatementInvalid

class BuildSegment::FindUsers 

    def initialize(params) 
    @key = User.connection.quote_column_name(params[:key]) 
    @negative = params[:negative] 
    @pattern = params[:pattern] 
    end 

    def call 
    if @negative 
     users = User.where.not("#{@key} LIKE ?", @pattern) 
    else 
     users = User.where("#{@key} LIKE ?", @pattern) 
    end 

    users.uniq 
    end 
end 

可变@key从哈希可以由被操纵采取用户。因此,举例来说,如果@key = "email LIKE '%' OR email",我路过@key直接到活动记录查询,我得到:

SELECT "users".* FROM "users" WHERE (email LIKE '%' OR email LIKE '') 

返回的所有用户。我发现quote_column_name(params[:key])作为返回ActiveRecord::StatementInvalid错误的解决方案:

ActiveRecord::StatementInvalid: 
     PG::UndefinedColumn: ERROR: column "email LIKE '%com%' OR email" does not exist 
     LINE 1: SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%... 
                  ^
     : SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%com%' OR email" LIKE '') 

这个测试,但是,失败:

expect(segment_builder.call).to raise_error(ActiveRecord::StatementError) 

和全回溯:

Failures: 

    1) BuildSegment is protected from SQL injection 
    Failure/Error: users_to_add = users.flatten 

    ActiveRecord::StatementInvalid: 
     PG::UndefinedColumn: ERROR: column "email LIKE '%com%' OR email" does not exist 
     LINE 1: SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%... 
                  ^
     : SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%com%' OR email" LIKE '') 
    # ./app/services/build_segment.rb:51:in `flatten' 
    # ./app/services/build_segment.rb:51:in `users_passing_all_rules' 
    # ./app/services/build_segment.rb:46:in `users_passing_filter' 
    # ./app/services/build_segment.rb:32:in `block in users_meeting_requirements_for' 
    # ./app/services/build_segment.rb:31:in `each' 
    # ./app/services/build_segment.rb:31:in `users_meeting_requirements_for' 
    # ./app/services/build_segment.rb:8:in `call' 
    # ./spec/services/build_segment_spec.rb:107:in `block (2 levels) in <top (required)>' 
    # ------------------ 
    # --- Caused by: --- 
    # PG::UndefinedColumn: 
    # ERROR: column "email LIKE '%com%' OR email" does not exist 
    # LINE 1: SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%... 
    #              ^
    # ./app/services/build_segment.rb:51:in `flatten' 

哪里可能是我的错误?

回答

0

它看起来像我不喜欢你的SQL正确逃脱。

看看这对你的作品:

User.where.not("#{@key} LIKE ?, '#{@pattern}'") 

User.where("#{@key} LIKE ?, '#{@pattern}'")