Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTML::StathamSanitizer
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(/</, "&lt;")
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(/</, "&lt;")
end
else
bad_tags.include?(options[:parent].first) ? nil : node.to_s.gsub(/</, "&lt;")
end
end
end
end
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 "&lt;font>Hello&lt;/font>", @sanitizer.sanitize("<font>Hello</font>")
end
should "escape tags that are allowed but unclosed" do
assert_equal "&lt;p>Hello", @sanitizer.sanitize("<p>Hello")
end
should "escape tags that are closed without ever being opened" do
assert_equal "Hello&lt;/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 "&lt;!-- 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