fix(html): apply export policies throughout template contents

Filter the template contents that are actually serialized and include reachable author shadow roots owned by inert Documents. Preserve inert iframe attributes without parsing or loading their raw srcdoc, and leave the live source unchanged.
This commit is contained in:
ldm0
2026-11-13 19:26:46 +08:00
committed by Donough Liu
parent 129b8cf640
commit 2d22d593b7
4 changed files with 105 additions and 34 deletions
@@ -139,16 +139,7 @@ impl DomHost {
explicit,
} => serializable && state.init.serializable() || explicit.contains(&state.handle),
// Only author roots enter this native registry; UA trees are renderer projections.
ShadowRootInclusion::AllAuthor => {
profile == ShadowRootMarkupProfile::Inspector
|| self
.dom
.node(host)
.and_then(Node::owner_document)
.and_then(|document| self.dom.node(document))
.and_then(Node::as_document)
.is_none_or(|document| !document.is_inert_template_document())
}
ShadowRootInclusion::AllAuthor => true,
};
if !included {
return None;
@@ -423,3 +423,59 @@ fn export_policy_filters_overrides_and_inserts_without_mutating_attributes() {
assert_eq!(host.dom().serialize_document(), before);
}
}
#[test]
fn export_visits_inert_shadow_roots_and_borrows_native_storage() {
use std::{cell::Cell, sync::Arc};
struct Policy<'a> {
dom: &'a NativeDom,
storage_refs: usize,
visited: Cell<usize>,
}
impl HtmlSerializationPolicy for Policy<'_> {
fn include_node(&self, node: &Node) -> bool {
assert_eq!(Arc::strong_count(&self.dom.nodes.chunks), self.storage_refs);
self.visited.set(self.visited.get() + 1);
!node.is_html_element_named("style")
}
fn include_shadow_adopted_style_sheets(&self) -> bool {
false
}
}
let mut host = DomHost::from_dom(NativeDom::new_html(test_url()));
host.reset_html_document_shell();
let body = host.document_body_handle().unwrap();
let template = host.create_element("template");
let contents = host.parser_template_contents_handle(template).unwrap();
let element = host.create_element("div");
assert!(host.append_child(contents, element));
assert!(host.append_child(body, template));
let mut init = ShadowRootInit::new("closed");
init.set_adopted_style_sheets(Some("data:text/css,b%7Bcolor:red%7D".into()));
let root = host.attach_shadow_root_with_init(element, init).unwrap();
let style = host.create_element("style");
let css = host.create_text_node("b{color:red}");
assert!(host.append_child(style, css));
let text = host.create_text_node("KEEP");
assert!(host.append_child(root, style));
assert!(host.append_child(root, text));
let before = host
.get_html_for_export(body, &scripting_enabled, None, None, None)
.unwrap();
assert!(before.contains("shadowrootadoptedstylesheets="));
let policy = Policy {
dom: host.dom(),
storage_refs: Arc::strong_count(&host.dom().nodes.chunks),
visited: Cell::new(0),
};
assert_eq!(
host.get_html_for_export(body, &scripting_enabled, Some(&policy), None, None)
.as_deref(),
Ok("<template><div><template shadowrootmode=\"closed\">KEEP</template></div></template>")
);
assert!(policy.visited.get() > 0);
assert_eq!(
host.get_html_for_export(body, &scripting_enabled, None, None, None),
Ok(before)
);
}
@@ -17,7 +17,6 @@ impl PageVm {
let vm = self.vm();
let dom = vm.document_runtime.dom_host().dom();
let policy = HtmlDumpPolicy {
dom,
strip: options.strip,
base: options
.with_base
@@ -33,35 +32,17 @@ impl PageVm {
}
}
struct HtmlDumpPolicy<'a> {
dom: &'a NativeDom,
struct HtmlDumpPolicy {
strip: RendererContentStripOptions,
base: Option<BaseInsertion>,
}
impl HtmlDumpPolicy<'_> {
fn is_inert_template_node(&self, node: &Node) -> bool {
node.owner_document()
.and_then(|document| self.dom.node(document))
.and_then(Node::as_document)
.is_some_and(|document| document.is_inert_template_document())
}
}
impl HtmlSerializationPolicy for HtmlDumpPolicy<'_> {
impl HtmlSerializationPolicy for HtmlDumpPolicy {
fn include_node(&self, node: &Node) -> bool {
self.is_inert_template_node(node)
|| !super::content_filter::should_strip_node(node, self.strip)
!super::content_filter::should_strip_node(node, self.strip)
}
fn include_attribute(&self, node: NativeNodeId, attribute: &Attribute) -> bool {
if self
.dom
.node(node)
.is_some_and(|node| self.is_inert_template_node(node))
{
return true;
}
fn include_attribute(&self, _: NativeNodeId, attribute: &Attribute) -> bool {
let name_start = attribute
.prefix()
.filter(|prefix| !prefix.is_empty())
@@ -229,7 +210,6 @@ mod tests {
let count = dom.nodes().len();
let version = host.dom_version();
let policy = HtmlDumpPolicy {
dom,
strip: Default::default(),
base: Some(BaseInsertion::new(dom, href)),
};
+44
View File
@@ -662,3 +662,47 @@ async fn html_dump_profiles_preserve_golden_markup_and_the_live_source() -> Resu
http_server.abort();
Ok(())
}
#[tokio::test]
async fn html_dump_filters_template_contents_and_includes_inert_author_shadow_roots() -> Result<()>
{
let (_browser, mut page, http_server) = load_page("<!doctype html><template id=content><nav>MENU</nav><script>secret=1</script><style>b{color:red}</style><div style=\"color:red\" onclick=\"void 0\">KEEP</div><x-card></x-card><iframe srcdoc=\"<script>inert=1</script><p>unparsed</p>\"></iframe></template>").await?;
let setup=page.evaluate_runtime_expression_by_value_async("document.getElementById('content').content.querySelector('x-card').attachShadow({mode:'closed'}).innerHTML='<style>b{color:red}</style><b>SHADOW</b>'; 'ready'").await?;
assert!(setup.get("exception").is_none(), "{setup}");
let before = page.serialize_html_async().await?;
assert!(
before.contains("shadowrootmode=\"closed\"") && before.contains("SHADOW"),
"{before}"
);
let output = render_page_dump_with_options_async(
&mut page,
DumpFormat::Html,
StripOptions {
js: true,
css: true,
ui: true,
},
false,
true,
false,
None,
)
.await?;
for removed in ["MENU", "secret=1", "color:red", "onclick="] {
assert!(!output.contains(removed), "{output}");
}
assert!(
output.contains("<div>KEEP</div>") && output.contains("<b>SHADOW</b>"),
"{output}"
);
// Inert owners have no live child Document. Preserve their raw srcdoc;
// exporting is not an HTML sanitizer and must not parse/load that string.
assert!(
output
.contains("srcdoc=\"&lt;script&gt;inert=1&lt;/script&gt;&lt;p&gt;unparsed&lt;/p&gt;\""),
"{output}"
);
assert_eq!(page.serialize_html_async().await?, before);
http_server.abort();
Ok(())
}