-
-
Save dwabnitz/254807 to your computer and use it in GitHub Desktop.
html sanitizer for use in rails - whitelisting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module HTML | |
class StathamSanitizer < WhiteListSanitizer | |
protected | |
def tokenize(text, options) | |
super.map do |token| | |
if token.is_a?(HTML::Tag) && options[:parent].include?(token.name) | |
token.to_s.gsub(/</, "<") | |
else | |
token | |
end | |
end | |
end | |
def process_node(node, result, options) | |
result << case node | |
when HTML::Tag | |
if node.closing == :close && options[:parent].first == node.name | |
options[:parent].shift | |
elsif node.closing != :self | |
options[:parent].unshift node.name | |
end | |
process_attributes_for node, options | |
if options[:tags].include?(node.name) | |
node | |
else | |
bad_tags.include?(node.name) ? nil : node.to_s.gsub(/</, "<") | |
end | |
else | |
bad_tags.include?(options[:parent].first) ? nil : node.to_s.gsub(/</, "<") | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require File.dirname(__FILE__) + '/../test_helper' | |
class StathamSanitizerTest < ActiveSupport::TestCase | |
context "A StathamSanitizer" do | |
setup do | |
@sanitizer = HTML::StathamSanitizer.new | |
end | |
should "escape tags that are neither allowed nor banned" do | |
assert_equal "<font>Hello</font>", @sanitizer.sanitize("<font>Hello</font>") | |
end | |
should "escape tags that are allowed but unclosed" do | |
assert_equal "<p>Hello", @sanitizer.sanitize("<p>Hello") | |
end | |
should "escape tags that are closed without ever being opened" do | |
assert_equal "Hello</p>", @sanitizer.sanitize("Hello</p>") | |
end | |
should "include tags that are allowed and self-closing" do | |
assert_equal "Hello<br />", @sanitizer.sanitize("Hello<br />") | |
end | |
should "escape comments" do | |
assert_equal "<!-- comment", @sanitizer.sanitize("<!-- comment") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment