Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a string, determine whether it is from an .html_safe call?

In Ruby on Rails, given a string, is it possible to determine whether .html_safe has been called on that string?

Reason for asking: I'd like to write a controller unit test that verifies that html_safe has not been called on a particular string, in order to prove that when that string later gets rendered onto a page in a view, Rails will escape the string (avoiding possible XSS vulnerabilities).

I realize that I could instead go ahead and actually render the page in my test, and then inspect the rendered page body, but I'm wondering if there's a more direct way of doing this?

like image 827
Jon Schneider Avatar asked Dec 17 '18 22:12

Jon Schneider


2 Answers

There's html_safe?:

s = 'foo'
s.html_safe? #=> false

s = 'foo'.html_safe
s.html_safe? #=> true

Note that an ActiveSupport::SafeBuffer reverts to unsafe if you call a "destructive" method:

s = 'foo'.html_safe
s.html_safe?  #=> true
s.capitalize! #=> 'Foo'
s.html_safe?  #=> false
like image 149
Stefan Avatar answered Nov 09 '22 20:11

Stefan


.html_safe actually returns not an object of type String, but an object of type ActiveSupport::SafeBuffer (which is a derived class of String).

Therefore, calling:

my_string.is_a?(ActiveSupport::SafeBuffer)

will return false only when the string is not the result of a call to .html_string.

like image 35
Jon Schneider Avatar answered Nov 09 '22 20:11

Jon Schneider