在RoR 4中使用验证的正则表达式

mal*_*uri 83 ruby activerecord ruby-on-rails

有以下代码:

class Product < ActiveRecord::Base
  validates :title, :description, :image_url, presence: true
  validates :price, numericality: {greater_than_or_equal_to: 0.01}
  validates :title, uniqueness: true
  validates :image_url, allow_blank: true, format: {
      with: %r{\.(gif|jpg|png)$}i,
      message: 'URL must point to GIT/JPG/PNG pictures'
  }
end
Run Code Online (Sandbox Code Playgroud)

它有效,但是当我尝试使用"rake test"测试它时,我会收到这条消息:

rake aborted!
The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?
Run Code Online (Sandbox Code Playgroud)

这是什么意思?我该如何解决?

old*_*god 154

^并且$Line of Line和End of Line锚点.虽然\A\z是永久开始字符串和结束串的锚.
看到不同:

string = "abcde\nzzzz"
# => "abcde\nzzzz"

/^abcde$/ === string
# => true

/\Aabcde\z/ === string
# => false
Run Code Online (Sandbox Code Playgroud)

所以Rails的告诉你,"你确定你想使用^$?难道你不希望使用\A\z呢?"

有关轨道安全问题的更多内容会在此处生成此警告.

  • 答案是:它是使用\ A和\ z而不是^和$因为在Ruby中,^和$只匹配换行符而不是字符串的开头和结尾,这允许javascript漏洞利用通过测试. (6认同)
  • 修复不必要的过时主义 (3认同)
  • 解释了它的要求,但没有回答如何解决它.我想如果你想使用^和$修复它的方法是在类的顶部添加:multiline => true? (2认同)

ole*_*ole 30

此警告会引发,因为您的验证规则容易被javascript注入.

在你的情况下\.(gif|jpg|png)$匹配到行尾.因此,您的规则将验证此值为pic.png\nalert(1);true:

"test.png\n<script>alert(1)</script>" === /\.(gif|jpg|png)$/i
# => true

"test.png\n<script>alert(1)</script>" === /\.(gif|jpg|png)\z/i
# => false
Run Code Online (Sandbox Code Playgroud)

阅读以下内容: