Ruby (Rails) unescape string - cancel Array.to_s

Several libraries were hacked and there was a problem when the line received "double escaped".

for example: fixed example

> x = ['a'] => ["a"] > x.to_s => "[\"a\"]" > 

Then back to

 \"\[\\\"s\\\"\]\" 

This happened when working with http headers. I have a header that will be an array, but the http library does this native escaping of characters by the value of array.to_s.

The workaround I found was to convert the array to a string by myself, and then β€œundo” to_s. Like this: formatted_value = value .to_s

 if value.instance_of?(Array) formatted_value = formatted_value.gsub(/\\/,"") #remove backslash formatted_value = formatted_value.gsub(/"/,"") #remove single quote formatted_value = formatted_value.gsub(/\[/,"") #remove [ formatted_value = formatted_value.gsub(/\]/,"") #remove ] end value = formatted_value 

... There should be a better way ... (without having to decapitate the gems that I use). (yes, this gap, if my line really contains these lines.)

Suggestions?

** UPDATE 2 **

Good. There are still problems in this area, but now I think I understood the main problem. It serializes my array in json after calling to_s. At least it looks like what I see.

[ 'a']. To_s.to_json

I call a method in gem that returns the results of to_s, and then I call to_json on it.

+4
source share
1 answer

I edited my answer due to your edited question:

I can not duplicate your results!

 >> x = ['a'] => ["a"] >> x.to_s => "a" 

But when I change the last call to this:

 >> x.inspect => "[\"a\"]" 

So, I will consider what you do?

this does not necessarily elude the meanings - as such. It saves the line as follows:

 %{["a"]} 

or rather:

 '["a"]' 

Anyway. This should work to undo it:

 >> x = ['a'] => ["a"] >> y = x.inspect => "[\"a\"]" >> z = Array.class_eval(y) => ["a"] >> x == z => true 

I am skeptical about the safety of using class_eval , but be careful with user inputs, because this can lead to unforeseen side effects (and by that I mean attacks on code injections), if you are not sure about where the source data came from or what they were allowed to.

+7
source

Source: https://habr.com/ru/post/1342850/


All Articles