Commit 1e85e9e5 authored by kaniini's avatar kaniini

sanitizer: rework a bit

parent 37e99fa3
Pipeline #11931 failed with stage
in 1 minute and 8 seconds
defmodule FastSanitize.Sanitizer do
require Logger
alias FastSanitize.Fragment
@moduledoc """
......@@ -21,18 +23,41 @@ defmodule FastSanitize.Sanitizer do
@callback scrub(binary()) :: binary()
# fallbacks
def scrub("", _), do: ""
def scrub(nil, _), do: ""
def scrub(doc, scrubber) do
with {:ok, subtree} <- Fragment.to_tree(doc) do
Enum.map(subtree, fn fragment ->
scrubber.scrub(fragment)
end)
def scrub("", _), do: {:ok, ""}
def scrub(nil, _), do: {:ok, ""}
def scrub(doc, scrubber) when is_binary(doc) do
with wrapped_doc <- "<body>" <> doc <> "</body>",
{:ok, subtree} <- Fragment.to_tree(wrapped_doc) do
scrub(subtree, scrubber)
|> Fragment.to_html()
else
e ->
{:error, e}
end
end
def scrub(subtree, scrubber) when is_list(subtree) do
Logger.debug("Pre-process: #{inspect(subtree)}")
Enum.map(subtree, fn fragment ->
case scrubber.scrub(fragment) do
{tag, attrs, nil} ->
Logger.debug("Post-process closure: #{inspect({tag, attrs, nil})}")
{tag, attrs, nil}
{tag, attrs, children} ->
Logger.debug("Post-process tag: #{inspect({tag, attrs, children})}")
{tag, attrs, scrub(children, scrubber)}
subtree when is_list(subtree) ->
Logger.debug("Post-process subtree: #{inspect(subtree)}")
scrub(subtree, scrubber)
other ->
Logger.debug("Post-process other: #{inspect(other)}")
other
end
end)
end
end
......@@ -17,7 +17,7 @@ defmodule FastSanitize.Fragment.Test do
test "it works for simple fragment trees with atypical tags" do
tree = [{:br, [], nil}, {:hr, [], nil}]
{:ok, "<br><hr>"} = FastSanitize.Fragment.to_html(tree)
{:ok, "<br /><hr />"} = FastSanitize.Fragment.to_html(tree)
end
test "it works for simple fragment trees with non-terminating tags" do
......@@ -30,7 +30,7 @@ defmodule FastSanitize.Fragment.Test do
], nil}
]
{:ok, "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://example.com/example.css\">"} =
{:ok, "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://example.com/example.css\"/>"} =
FastSanitize.Fragment.to_html(tree)
end
end
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment