开发者

Sanitizing User Input with Ruby on Rails

I'm writing a very simple CRUD app that takes user stories and stores them into a database so another fellow coder can organize them for a project we're both working on. However, I have come across a problem with sanitizing user input before it is saved into the database. I cannot call the sanitize() function from within the Story model to strip out all of the html/scripting. It requires me to do the following:

def sanitize_inputs
  self.name =  ActionController::Base.helpe开发者_高级运维rs.sanitize(self.name) unless self.name.nil?
  self.story = ActionController::Base.helpers.sanitize(self.story) unless self.story.nil?
end

I want to validate that the user input has been sanitized and I am unsure of two things: 1) When should the user input validation take place? Before the data is saved is pretty obvious, I think, however, should I be processing this stuff in the Controller, before validation, or some other non-obvious area before I validate that the user input has no scripting/html tags? 2) Writing a unit test for this model, how would I verify that the scripting/html is removed besides comparing "This is a malicious code example" to the sanitize(example) output?

Thanks in advance.


There are 2 approaches to eliminate XSS vulnerabilities:

A.To filter the content before storing it in the DB (What you are trying to do). Here are 2 plugins that do this for you.

xss_terminate

acts_as_sanitiled

B.To filter the content when you display it (Rails 3 does it by default). You can either use the h function or use rails_xss.

As with your second question, i think your unit test should only test that the sanitizing method is called, not the functionality itself(so a simple assertion on a basic example should do the trick). The sanitizing functions/plugins are already very well tested by default.


I think the general consensus on sanitizing input is -- don't. Store the input as the user entered it and use the sanitize helper on output. (e.g, <%=h @author.filthy_nasty_data %>)

That said, you could always use the strip_tags helper as mentioned in this answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜