简体   繁体   中英

Rails form text_field escaping html

Experimenting with my Rails form, I find that inserting <scrip>alert("hello")</script> into a text_field gives me two different results.

When I use the value, for example in a display page, it is automagicaly escaped.

When I use the value in a new form, for example to allow user editing, it is not escaped and I get the alert pop-up.

After a lot of research, I have found that text_area has an escape boolean that prevents this, but not text_field. Most of the stuff coming up on google is about escaping within erb templates, which does not appear to work when using a form. There are a couple of hints that data should be sanitized going into the db, but little guidance on the best way to do this --- aside from using old solutions for example xssterminate which appears to date back to Rails 2. Even the RoR security guide focuses on sanitizing erb output rather than santizing the input.

Two questions.

  1. What is the current best-practice approach to sanitizing text_field input before it is saved? (eg: in the form, the controller or the model. What gems are still considered current?)
  2. Regardless, because I am paranoid, how do you sanitize the text_field when displaying db data?

The loofah-activerecord gem ( https://github.com/flavorjones/loofah-activerecord ) looks like your best bet for sanitizing data on its way into the database. Using xss_foliate on your models will strip tags for all columns by default.

eg

class User < ActiveRecord::Base
  xss_foliate

  ...
end

I haven't found a solution to the 2nd point, but would be very keen to know about it if there is one!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM