From 5d10d3b07ecaf07ae1f937a3216c26231603c95c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Olav=20Ringstad?= Date: Wed, 2 Oct 2019 13:31:38 +0200 Subject: [PATCH] Fixed classcast error in post processing of nodes When you use SanitizeDocument the 'context' parameter of DoPostProcess and RemoveComments is set to be the HTML document itself. The post processing require the context to be an IElement which isn't the case for AngleSharps HtmlDocument. Changed signatures of methods in post processing to use an INode instead. This allows the PostProcessNode event to be called when using SanitizeDocument. --- src/HtmlSanitizer/HtmlSanitizer.cs | 12 ++++++------ test/HtmlSanitizer.Tests/Tests.cs | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/HtmlSanitizer/HtmlSanitizer.cs b/src/HtmlSanitizer/HtmlSanitizer.cs index ead8a67..01deb51 100644 --- a/src/HtmlSanitizer/HtmlSanitizer.cs +++ b/src/HtmlSanitizer/HtmlSanitizer.cs @@ -629,9 +629,9 @@ namespace Ganss.XSS /// /// Removes all comment nodes from a list of nodes. /// - /// The element within which to remove comments. + /// The node within which to remove comments. /// true if any comments were removed; otherwise, false. - private void RemoveComments(IElement context) + private void RemoveComments(INode context) { foreach (var comment in GetAllNodes(context).OfType().ToList()) { @@ -707,9 +707,9 @@ namespace Ganss.XSS } } - RemoveComments(context as IElement); + RemoveComments(context as INode); - DoPostProcess(dom, context as IElement); + DoPostProcess(dom, context as INode); } private void SanitizeStyleSheets(IHtmlDocument dom, string baseUrl) @@ -775,8 +775,8 @@ namespace Ganss.XSS /// Performs post processing on all nodes in the document. /// /// The HTML document. - /// The element within which to post process all nodes. - private void DoPostProcess(IHtmlDocument dom, IElement context) + /// The node within which to post process all nodes. + private void DoPostProcess(IHtmlDocument dom, INode context) { if (PostProcessNode != null) { diff --git a/test/HtmlSanitizer.Tests/Tests.cs b/test/HtmlSanitizer.Tests/Tests.cs index e4b993a..a443c1f 100644 --- a/test/HtmlSanitizer.Tests/Tests.cs +++ b/test/HtmlSanitizer.Tests/Tests.cs @@ -2187,6 +2187,25 @@ rl(javascript:alert(""foo""))'>"; Assert.Equal(@"
HalloTest
", sanitized, ignoreCase: true); } + [Fact] + public void PostProcessNodeTestUsingDocument() + { + var sanitizer = new HtmlSanitizer(); + sanitizer.PostProcessNode += (s, e) => + { + if (e.Node is IHtmlDivElement el) + { + el.ClassList.Add("test"); + var b = e.Document.CreateElement("b"); + b.TextContent = "Test"; + el.AppendChild(b); + } + }; + var html = @"
Hallo
"; + var sanitized = sanitizer.SanitizeDocument(html); + Assert.Equal(@"
HalloTest
", sanitized, ignoreCase: true); + } + [Fact] public void PostProcessDomTest() {