[英]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. 我正在编写一个非常简单的CRUD应用程序,该应用程序将用户故事存储到数据库中,以便其他编码人员可以为我们正在处理的项目组织它们。 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.
我无法从Story模型中调用sanitize()函数来去除所有的html /脚本。 It requires me to do the following:
它要求我做以下事情:
def sanitize_inputs
self.name = ActionController::Base.helpers.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? 我想验证用户输入是否已经过消毒,我不确定两件事:1)用户输入验证应该何时进行? 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?
在保存数据之前是非常明显的,但是,我认为,在验证用户输入没有脚本/ html标记之前,我应该在验证之前处理Controller中的这些内容,还是其他一些非显而易见的区域? 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?
2)为此模型编写单元测试,除了将“这是恶意代码示例”与清理(示例)输出进行比较之外,如何验证脚本/ html是否被删除?
Thanks in advance. 提前致谢。
There are 2 approaches to eliminate XSS vulnerabilities: 有两种方法可以消除XSS漏洞:
A.To filter the content before storing it in the DB (What you are trying to do). A.在将内容存储到数据库之前过滤内容(您要做的是什么)。 Here are 2 plugins that do this for you.
这里有2个插件可以帮到你。
acts_as_sanitiled acts_as_sanitiled
B.To filter the content when you display it (Rails 3 does it by default). B.在显示内容时过滤内容(Rails 3默认情况下会这样做)。 You can either use the
h
function or use rails_xss . 您可以使用
h
函数或使用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. 在用户输入时存储输入并在输出上使用
sanitize
帮助器。 (eg, <%=h @author.filthy_nasty_data %>
) (例如,
<%=h @author.filthy_nasty_data %>
)
That said, you could always use the strip_tags
helper as mentioned in this answer . 也就是说,你总是可以使用本回答中提到的
strip_tags
助手。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.