Skip to content

Instantly share code, notes, and snippets.

@NZKoz
Created June 7, 2011 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NZKoz/392235903426322e0414 to your computer and use it in GitHub Desktop.
Save NZKoz/392235903426322e0414 to your computer and use it in GitHub Desktop.
rails_xss
diff --git a/lib/rails_xss/string_ext.rb b/lib/rails_xss/string_ext.rb
index ae21705..ed1aaa2 100644
--- a/lib/rails_xss/string_ext.rb
+++ b/lib/rails_xss/string_ext.rb
@@ -9,6 +9,19 @@ ActiveSupport::SafeBuffer.class_eval do
end
end
alias << concat
+ UNSAFE_STRING_METHODS = ["capitalize", "chomp", "chop", "delete", "downcase", "gsub", "lstrip", "next", "reverse", "rstrip", "slice", "squeeze", "strip", "sub", "succ", "swapcase", "tr", "tr_s", "upcase"].freeze
+
+ for unsafe_method in UNSAFE_STRING_METHODS
+ class_eval <<-EOT, __FILE__, __LINE__
+ def #{unsafe_method}(*args)
+ super.to_str
+ end
+
+ def #{unsafe_method}!(*args)
+ raise TypeError, "Cannot modify SafeBuffer in place"
+ end
+ EOT
+ end
end
class String
diff --git a/test/safe_buffer_test.rb b/test/safe_buffer_test.rb
index 6a515da..cf3b5f5 100644
--- a/test/safe_buffer_test.rb
+++ b/test/safe_buffer_test.rb
@@ -38,4 +38,14 @@ class SafeBufferTest < ActiveSupport::TestCase
new_buffer = @buffer.to_s
assert_equal ActiveSupport::SafeBuffer, new_buffer.class
end
+
+ test "Should not return a safe buffer when using sub" do
+ assert !@buffer.sub('', "asdf").html_safe?
+ end
+
+ test "Should raise argument error when using sub!" do
+ assert_raise ArgumentError do
+ @buffer.sub!('', "asdf")
+ end
+ end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment