Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: scrub_css is more consistent with whitespace #273

Merged
merged 1 commit into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions lib/loofah/html5/scrub.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module Scrub
CSS_KEYWORDISH = /\A(#[0-9a-fA-F]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|-?\d{0,3}\.?\d{0,10}(ch|cm|r?em|ex|in|lh|mm|pc|pt|px|Q|vmax|vmin|vw|vh|%|,|\))?)\z/ # rubocop:disable Layout/LineLength
CRASS_SEMICOLON = { node: :semicolon, raw: ";" }
CSS_IMPORTANT = "!important"
CSS_WHITESPACE = " "
CSS_PROPERTY_STRING_WITHOUT_EMBEDDED_QUOTES = /\A(["'])?[^"']+\1\z/
DATA_ATTRIBUTE_NAME = /\Adata-[\w-]+\z/

Expand Down Expand Up @@ -87,7 +88,7 @@ def scrub_css(style)
value = node[:children].map do |child|
case child[:node]
when :whitespace
nil
CSS_WHITESPACE
when :string
if CSS_PROPERTY_STRING_WITHOUT_EMBEDDED_QUOTES.match?(child[:raw])
Crass::Parser.stringify(child)
Expand All @@ -106,12 +107,12 @@ def scrub_css(style)
else
child[:raw]
end
end.compact
end.compact.join.strip

next if value.empty?

value << CSS_IMPORTANT if node[:important]
propstring = format("%s:%s", name, value.join(" "))
value << CSS_WHITESPACE << CSS_IMPORTANT if node[:important]
propstring = format("%s:%s", name, value)
sanitized_node = Crass.parse_properties(propstring).first
sanitized_tree << sanitized_node << CRASS_SEMICOLON
end
Expand Down
20 changes: 20 additions & 0 deletions test/html5/test_scrub_css.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,26 @@ class UnitHTML5Scrub < Loofah::TestCase
assert_empty(Loofah::HTML5::Scrub.scrub_css('font-family:"AvenirNext-Regular;'))
assert_empty(Loofah::HTML5::Scrub.scrub_css(%q(font-family:"AvenirNext-Regular';)))
end

it "keeps whitespace around delimiters if it's already there" do
assert_equal(
"font:13px / 1.5 Arial , sans-serif;",
Loofah::HTML5::Scrub.scrub_css("font: 13px / 1.5 Arial , sans-serif;"),
)
end

it "does not insert spaces around delimiters if they aren't already there" do
assert_equal(
"font:13px/1.5 Arial, sans-serif;",
Loofah::HTML5::Scrub.scrub_css("font: 13px/1.5 Arial, sans-serif;"),
)
end
end

describe "whitespace" do
it "converts all whitespace to a single space except initial and final whitespace" do
assert_equal("font:12px Arial;", Loofah::HTML5::Scrub.scrub_css("font: \n\t 12px \n\t Arial \n\t ;"))
end
end

describe "colors" do
Expand Down