Skip to content

Lightpanda: the headless browser designed for AI and automation

crash: Prevent node cycles when the parser reparents moved nodes

Karl Seguind5e4a000a979
diff --git a/src/browser/parser/Parser.zig b/src/browser/parser/Parser.zig
index f33dcbd53..1bd8c7e71 100644
--- a/src/browser/parser/Parser.zig
+++ b/src/browser/parser/Parser.zig
@@ -747,8 +747,12 @@ fn _appendCallback(self: *Parser, parent_pn: *ParsedNode, node_or_text: h5e.Node
try self.flushPendingText();
self.maybeCheckpoint();
self.inserted_since_checkpoint +|= 1;
- const child = try self.settleDocument(parent_pn, getParsed(cpn));
const parent = parent_pn.node;
+ if (wouldCycle(getParsed(cpn).node, parent)) {
+ // Inserting would build a cycle (script moved it inside the adopting node)
+ return;
+ }
+ const child = try self.settleDocument(parent_pn, getParsed(cpn));
if (child._parent) |previous_parent| {
// html5ever says this can't happen, but we might be screwing up
// the node on our side. We shouldn't be, but we're seeing this
@@ -896,6 +900,10 @@ fn _appendBeforeSiblingCallback(self: *Parser, sibling_pn: *ParsedNode, node_or_
const parent = sibling.parentNode() orelse return error.NoParent;
const node: *Node = switch (node_or_text.toUnion()) {
.node => |cpn| blk: {
+ if (wouldCycle(getParsed(cpn).node, parent)) {
+ // See _appendCallback: the would-be cycle drops the node.
+ return;
+ }
var parent_pn = ParsedNode{ .node = parent, .data = null, .placed = true };
const child = try self.settleDocument(&parent_pn, getParsed(cpn));
if (child._parent) |previous_parent| {
@@ -935,6 +943,26 @@ fn _appendBasedOnParentNodeCallback(self: *Parser, element_pn: *ParsedNode, prev
}
}
+fn wouldCycle(node: *Node, parent: *Node) bool {
+ if (node == parent) {
+ return true;
+ }
+ // we can optimize this a bit and avoid calling `isHostIncludingInclusiveAncestorOf`
+ // in some cases
+ if (node.firstChild() == null) {
+ const element = node.is(Element) orelse return false;
+ if (element._flags.shadow_host == false) {
+ const template = element.is(Element.Html.Template) orelse return false;
+ if (template._content.asNode().firstChild() == null) {
+ // the node has no child and it isn't a template with children
+ // (it can't contain parent then)
+ return false;
+ }
+ }
+ }
+ return node.isHostIncludingInclusiveAncestorOf(parent);
+}
+
fn getParsed(ref: *anyopaque) *ParsedNode {
return @ptrCast(@alignCast(ref));
}
diff --git a/src/browser/tests/frames/srcdoc.html b/src/browser/tests/frames/srcdoc.html
index debd1333d..be6092149 100644
--- a/src/browser/tests/frames/srcdoc.html
+++ b/src/browser/tests/frames/srcdoc.html
@@ -181,3 +181,30 @@
});
}
</script>
+
+<script id=adoption_agency_cycle type=module>
+ {
+ // Script moves the adoption agency's common ancestor (#ca) inside its
+ // furthest block (#fb), directly, across a shadow root, or into template
+ // contents. Moving #fb into #ca would be a cycle; the parser drops it.
+ const moves = [
+ "fb.appendChild(ca)",
+ "var h=document.createElement('span');var r=h.attachShadow({mode:'open'});fb.appendChild(h);r.appendChild(ca)",
+ "var t=document.createElement('template');fb.appendChild(t);t.content.appendChild(ca)",
+ ];
+ for (const move of moves) {
+ const state = await testing.async();
+ const f = document.createElement('iframe');
+ f.srcdoc = `<div id=ca><b><p id=fb><script>var fb=document.getElementById('fb');var ca=document.getElementById('ca');document.body.appendChild(fb);${move}<\/script></b></div>`;
+ f.onload = () => state.resolve(f);
+ document.body.appendChild(f);
+
+ await state.done((f) => {
+ const w = f.contentWindow;
+ testing.expectEqual(0, f.contentDocument.body.childNodes.length);
+ testing.expectEqual(null, w.fb.parentNode);
+ testing.expectEqual(false, w.ca.contains(w.fb));
+ });
+ }
+ }
+</script>
diff --git a/src/browser/tests/node/append_child.html b/src/browser/tests/node/append_child.html
index 20c98987c..22fb293f3 100644
--- a/src/browser/tests/node/append_child.html
+++ b/src/browser/tests/node/append_child.html
@@ -93,3 +93,23 @@
testing.expectEqual(detached, ood.parentNode);
testing.expectEqual(detached, parentSeenAtDisconnect);
</script>
+
+<script id=appendChild_host_including_cycle>
+ {
+ // Inserting a node under its own shadow root or template contents is a
+ // cycle through the host, not just a same-tree containment.
+ const outer = document.createElement('div');
+ const host = document.createElement('span');
+ outer.appendChild(host);
+ const root = host.attachShadow({mode: 'open'});
+ testing.expectError('HierarchyRequestError', () => root.appendChild(outer));
+ testing.expectError('HierarchyRequestError', () => root.appendChild(host));
+ testing.expectEqual(null, outer.parentNode);
+
+ const tmpl = document.createElement('template');
+ outer.appendChild(tmpl);
+ testing.expectError('HierarchyRequestError', () => tmpl.content.appendChild(outer));
+ testing.expectError('HierarchyRequestError', () => tmpl.content.insertBefore(tmpl, null));
+ testing.expectEqual(0, tmpl.content.childNodes.length);
+ }
+</script>
diff --git a/src/browser/webapi/DocumentFragment.zig b/src/browser/webapi/DocumentFragment.zig
index 0457361f0..40af05525 100644
--- a/src/browser/webapi/DocumentFragment.zig
+++ b/src/browser/webapi/DocumentFragment.zig
@@ -23,6 +23,7 @@ const Frame = @import("../Frame.zig");
const Node = @import("Node.zig");
const Element = @import("Element.zig");
const ShadowRoot = @import("ShadowRoot.zig");
+const Template = @import("element/html/Template.zig");
const collections = @import("collections.zig");
const Selector = @import("selector/Selector.zig");
@@ -32,6 +33,7 @@ pub const Proto = Node;
_type: Type,
_proto: *Node,
+_template: ?*Template = null,
pub const Type = union(enum) {
generic,
@@ -61,6 +63,13 @@ pub fn init(document: *const Node.Document, frame: *Frame) !*DocumentFragment {
});
}
+pub fn getHost(self: *const DocumentFragment) ?*Element {
+ return switch (self._type) {
+ .shadow_root => |shadow_root| shadow_root._host,
+ .generic => if (self._template) |template| template.asElement() else null,
+ };
+}
+
pub fn asNode(self: *DocumentFragment) *Node {
return self._proto;
}
diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zig
index 4e885bbf9..5a48c578a 100644
--- a/src/browser/webapi/Node.zig
+++ b/src/browser/webapi/Node.zig
@@ -249,7 +249,7 @@ fn validateNodeInsertion(parent: *Node, node: *Node) !void {
}
// Check if node contains parent (would create a cycle)
- if (node.contains(parent)) {
+ if (node.isHostIncludingInclusiveAncestorOf(parent)) {
return error.HierarchyError;
}
@@ -274,7 +274,7 @@ fn ensurePreInsertValidity(parent: *Node, node: *Node, child: ?*Node, comptime m
else => return error.HierarchyError,
}
- if (node.contains(parent)) {
+ if (node.isHostIncludingInclusiveAncestorOf(parent)) {
return error.HierarchyError;
}
@@ -700,6 +700,20 @@ pub fn contains(self: *const Node, child_: ?*const Node) bool {
return false;
}
+// Like contains(), but also climbs from a shadow root or template contents.
+pub fn isHostIncludingInclusiveAncestorOf(self: *const Node, other: *Node) bool {
+ var node = other;
+ while (node != self) {
+ if (node._parent) |parent| {
+ node = parent;
+ } else {
+ const fragment = node.is(DocumentFragment) orelse return false;
+ node = (fragment.getHost() orelse return false).asNode();
+ }
+ }
+ return true;
+}
+
pub fn ownerDocument(self: *const Node, frame: *const Frame) ?*Document {
// A document node does not have an owner.
if (self._type == .document) {
@@ -967,7 +981,7 @@ pub fn moveBefore(self: *Node, node_val: js.Value, child_val: js.Value, frame: *
else => return error.HierarchyError,
}
- if (node.contains(self)) {
+ if (node.isHostIncludingInclusiveAncestorOf(self)) {
return error.HierarchyError;
}
diff --git a/src/browser/webapi/element/html/Template.zig b/src/browser/webapi/element/html/Template.zig
index 7bafd2973..c0ad45581 100644
--- a/src/browser/webapi/element/html/Template.zig
+++ b/src/browser/webapi/element/html/Template.zig
@@ -161,6 +161,7 @@ pub const Build = struct {
// owner document, not to the template's own document.
const owner = try node.getDocument(frame).templateContentsOwner(frame);
self._content = try DocumentFragment.init(owner, frame);
+ self._content._template = self;
}
// Per the HTML spec's cloning steps for <template>, a deep clone must