require 'test/unit'
require File.expand_path(File.join(File.dirname(__FILE__), '../../../../config/environment.rb'))
class WhiteListTest < Test::Unit::TestCase
include WhiteListHelper
public :contains_bad_protocols?
WhiteListHelper.tags.each do |tag_name|
define_method "test_should_allow_#{tag_name}_tag" do
assert_white_listed "start <#{tag_name} title=\"1\" name=\"foo\">foo bar baz#{tag_name}> end", "start <#{tag_name} title='1'>foo <bad>bar</bad> baz#{tag_name}> end"
end
end
def test_should_allow_anchors
assert_white_listed %(), ""
end
%w(src width height alt).each do |img_attr|
define_method "test_should_allow_image_#{img_attr}_attribute" do
assert_white_listed %(), ""
end
end
def test_should_handle_non_html
assert_white_listed 'abc'
end
def test_should_handle_blank_text
assert_white_listed nil
assert_white_listed ''
end
def test_should_allow_custom_tags
text = "foo"
assert_equal(text, white_list(text, :tags => %w(u)))
end
def test_should_allow_custom_tags_with_attributes
text = "
"
assert_equal(text, white_list(text, :attributes => ['foo']))
end
[%w(img src), %w(a href)].each do |(tag, attr)|
define_method "test_should_strip_#{attr}_attribute_in_#{tag}_with_bad_protocols" do
assert_white_listed %(<#{tag} #{attr}="javascript:bang" title="1">boo#{tag}>), %(<#{tag} title='1'>boo#{tag}>)
end
end
def test_should_flag_bad_protocols
%w(about chrome data disk hcp help javascript livescript lynxcgi lynxexec ms-help ms-its mhtml mocha opera res resource shell vbscript view-source vnd.ms.radio wysiwyg).each do |proto|
assert contains_bad_protocols?("#{proto}://bad")
end
end
def test_should_accept_good_protocols
WhiteListHelper.protocols.each do |proto|
assert !contains_bad_protocols?("#{proto}://good")
end
end
def test_should_reject_hex_codes_in_protocol
assert contains_bad_protocols?("%6A%61%76%61%73%63%72%69%70%74%3A%61%6C%65%72%74%28%22%58%53%53%22%29")
assert_white_listed %(1), "1"
end
def test_should_block_script_tag
assert_white_listed %(), ""
end
[%(),
%(),
%(),
%(">),
%(),
%(),
%(),
%(),
%(),
%(),
%(),
%(),
%(),
%(),
%()].each_with_index do |img_hack, i|
define_method "test_should_not_fall_for_xss_image_hack_#{i}" do
assert_white_listed img_hack, ""
end
end
def test_should_sanitize_tag_broken_up_by_null
assert_white_listed %(alert(\"XSS\")), "<scr>alert(\"XSS\")</scr>"
end
def test_should_sanitize_invalid_script_tag
assert_white_listed %(), ""
end
def test_should_sanitize_script_tag_with_multiple_open_brackets
assert_white_listed %(<), "<"
assert_white_listed %(<"
end
def test_should_sanitize_unclosed_script
assert_white_listed %(blah)
safe = white_list html do |node, bad|
bad == 'script' ? nil : node
end
assert_equal "blah", safe
end
protected
def assert_white_listed(text, expected = nil)
assert_equal((expected || text), white_list(text))
end
end