Skip to content

Sanitize while parsing - #12756

Merged
zcorpan merged 9 commits into
mainfrom
noamr/streaming-sanitizer
Oct 13, 2026
Merged

zcorpan merged 9 commits into
mainfrom
noamr/streaming-sanitizer

Conversation

@noamr

@noamr noamr commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Sanitize while parsing, instead of parsing into a fragment and then walking it.

The sanitizer configuration is passed into the HTML parser, which consults it wherever it would create or insert a node: disallowed elements are never created or inserted (or are replaced by their children, by redirecting insertions to where the element would have gone), disallowed attributes are dropped before the element is created, and disallowed comments and processing instructions are discarded. The separate post-parse "sanitize" algorithm is gone; the safe variants are expressed by applying their restrictions to the configuration up front.

Consequences of doing this in the parser:

  • No custom element constructors run for elements the sanitizer discards (they get no definition and a null registry), and no speculative fetches are started while sanitizing.
  • When sanitizing, fragment parsing builds its result in the inert document and adopts it into the target afterwards, so discarded elements never exist in the target document (Nodes are made non-inert before sanitizing #12560).
  • Declarative shadow roots are only attached when <template> and shadowrootmode survive the configuration; <template for> patching as well.
  • Insertion locations are computed after element creation, since creating a customized built-in can run script. The adoption agency algorithm and the Noah's Ark clause are adjusted so that removed/replaced elements and stripped attributes don't affect them (the latter now compares token attributes, matching all engines).

Web-observable changes compared to the post-parse sanitizer:

@noamr noamr closed this Aug 4, 2026
@noamr noamr reopened this Aug 4, 2026
@noamr noamr mentioned this pull request Aug 4, 2026
5 tasks done
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 7b105e3 to e24c23b Compare August 5, 2026 09:31
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch 3 times, most recently from 4ff3705 to 8551681 Compare August 7, 2026 20:17

@zcorpan zcorpan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing null check; nits.

Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch 2 times, most recently from 1d9e935 to 4453c2a Compare August 12, 2026 16:07
@noamr noamr closed this Aug 13, 2026
@noamr noamr reopened this Aug 13, 2026
Comment thread source Resolved
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 4453c2a to 931141c Compare August 14, 2026 08:52
@noamr
noamr requested a review from zcorpan August 14, 2026 08:57
Comment thread source Resolved
Comment thread source Resolved
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 32e5b9a to 1b77b8d Compare August 15, 2026 10:04
brave-builds pushed a commit to brave/chromium that referenced this pull request Aug 17, 2026
Sanitization should take place while performing the adoption agency
algorithm, otherwise some nodes can be missed.

Since adoption agency often adds an intermediate element,
the ReplaceWithChildren directive essentially negates it,
while Remove reparents the children into the intermediate
element and removes all of them.

This is in line with spec changes made as part of
whatwg/html#12756

Bug: 498272014
Change-Id: Ieb755555635e197f8ed7daf06a08679a0f2d38c3
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/8250959
Commit-Queue: Noam Rosenthal <nrosenthal@google.com>
Reviewed-by: Daniel Vogelheim <vogelheim@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1680770}
chromium-wpt-export-bot pushed a commit to web-platform-tests/wpt that referenced this pull request Aug 17, 2026
Sanitization should take place while performing the adoption agency
algorithm, otherwise some nodes can be missed.

Since adoption agency often adds an intermediate element,
the ReplaceWithChildren directive essentially negates it,
while Remove reparents the children into the intermediate
element and removes all of them.

This is in line with spec changes made as part of
whatwg/html#12756

Bug: 498272014
Change-Id: Ieb755555635e197f8ed7daf06a08679a0f2d38c3
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/8250959
Commit-Queue: Noam Rosenthal <nrosenthal@google.com>
Reviewed-by: Daniel Vogelheim <vogelheim@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1680770}
chromium-wpt-export-bot pushed a commit to web-platform-tests/wpt that referenced this pull request Aug 17, 2026
Sanitization should take place while performing the adoption agency
algorithm, otherwise some nodes can be missed.

Since adoption agency often adds an intermediate element,
the ReplaceWithChildren directive essentially negates it,
while Remove reparents the children into the intermediate
element and removes all of them.

This is in line with spec changes made as part of
whatwg/html#12756

Bug: 498272014
Change-Id: Ieb755555635e197f8ed7daf06a08679a0f2d38c3
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/8250959
Commit-Queue: Noam Rosenthal <nrosenthal@google.com>
Reviewed-by: Daniel Vogelheim <vogelheim@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1680770}
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 1b77b8d to 2eb51b7 Compare August 19, 2026 16:22
@zcorpan

zcorpan commented Oct 12, 2026

Copy link
Copy Markdown
Member
AI review

Reviewed at d5dcf0ca, covering 3154bcbf and d5dcf0ca since 72ba4a98. The fix for replaced-element children, the processing-instruction and elements matching fixes, the dropped inert-document registry step and the Document assert all look right to me. One new problem:

Blockers

  • source:147136-147145: using the host's custom element registry for the declarative shadow root changes DSR parsing everywhere, not just when sanitizing.
    • The rationale is wrong. The reply says this matches attachShadow(), but DOM's attachShadow() step 1 defaults to the host's node document's custom element registry, which is what this step said before.
    • Normal page parsing changes. Take <div><template shadowrootmode=open shadowrootcustomelementregistry><span><template shadowrootmode=open><x-foo> in a page. span has a null registry, so the inner shadow root now gets null instead of the document's global registry, and x-foo is no longer upgraded.
    • Chromium uses the document's global registry (Element::AttachDeclarativeShadowRoot, element.cc:8049-8054).
    • The fix is simpler now. With the inert-document registry step gone, the node document's registry is null in every sanitizing parse: the inert fragment document, and the new Document in parseHTML()/parseHTMLUnsafe(). So reverting to the node document's registry fixes the removed-host case without changing anything else. Consider reverting it and adjusting the note.

Suggestions

  • These earlier points are still open as far as I can tell:
    • Nested elements are now created in the inert document for plain innerHTML, e.g. <p><video poster> ends up with no poster frame (source:151729, 151776).
    • hostIsRoot checks the adjusted current node (source:147043).
    • The two wpt expectation bugs (sethtml-tree-construction.sub.dat:942-945 and sethtml-with-declarative-shadow-root.tentative.html:66), and the coverage gaps.
    • The PR description still describes a "sanitize" algorithm on a single Element, and still says MDN isn't affected.

Nits

  • source:145974-145976: "and registry if sanitizerAction is "Keep" or null otherwise" is hard to parse. Consider "…, and registry if sanitizerAction is "Keep"; otherwise null."

@noamr

noamr commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

AI review
Reviewed at d5dcf0ca, covering 3154bcbf and d5dcf0ca since 72ba4a98. The fix for replaced-element children, the processing-instruction and elements matching fixes, the dropped inert-document registry step and the Document assert all look right to me. One new problem:

Blockers

  • source:147136-147145: using the host's custom element registry for the declarative shadow root changes DSR parsing everywhere, not just when sanitizing.

    • The rationale is wrong. The reply says this matches attachShadow(), but DOM's attachShadow() step 1 defaults to the host's node document's custom element registry, which is what this step said before.
    • Normal page parsing changes. Take <div><template shadowrootmode=open shadowrootcustomelementregistry><span><template shadowrootmode=open><x-foo> in a page. span has a null registry, so the inner shadow root now gets null instead of the document's global registry, and x-foo is no longer upgraded.
    • Chromium uses the document's global registry (Element::AttachDeclarativeShadowRoot, element.cc:8049-8054).
    • The fix is simpler now. With the inert-document registry step gone, the node document's registry is null in every sanitizing parse: the inert fragment document, and the new Document in parseHTML()/parseHTMLUnsafe(). So reverting to the node document's registry fixes the removed-host case without changing anything else. Consider reverting it and adjusting the note.

Suggestions

  • These earlier points are still open as far as I can tell:

    • Nested elements are now created in the inert document for plain innerHTML, e.g. <p><video poster> ends up with no poster frame (source:151729, 151776).
    • hostIsRoot checks the adjusted current node (source:147043).
    • The two wpt expectation bugs (sethtml-tree-construction.sub.dat:942-945 and sethtml-with-declarative-shadow-root.tentative.html:66), and the coverage gaps.
    • The PR description still describes a "sanitize" algorithm on a single Element, and still says MDN isn't affected.

Nits

  • source:145974-145976: "and registry if sanitizerAction is "Keep" or null otherwise" is hard to parse. Consider "…, and registry if sanitizerAction is "Keep"; otherwise null."

This is sorted.
Part of this was a wild goose chase from the previous AI review that I should have ignored :/

@zcorpan

zcorpan commented Oct 12, 2026

Copy link
Copy Markdown
Member

Sorry about the goose chase. Maybe noamr/web-archeologist#10 will help.

AI review

Reviewed at 7dec21df, covering 5bdc4612, ae18e134 and 7dec21df since d5dcf0ca, together with wpt#62492 at ddc809a9. The spec changes look right:

  • The DSR registry is back to the host's node document's registry, and the note's claim holds: the inert document and the parseHTML*() Document both have a null registry.
  • The safe default now goes through configure, remove unsafe and the validity assert.
  • The wording nit is fixed.
  • The wpt bugs are fixed, the .tentative names are dropped, and most of the coverage gaps now have tests.

Suggestions

  • source:147041: using the current node as the declarative shadow host is normative for every fragment parse, not just sanitizing ones. It matches Chrome Canary 157, Fx Nightly 160 and Safari TP (div.setHTMLUnsafe('<template shadowrootmode=open>x</template>y') gives no shadow root and 2 children). Consider mentioning it in the commit message.
  • PR description:
    • The new "Web-observable changes" list contradicts the checklist, which still says "This mostly keeps existing behavior. The observable difference is coalescing of text nodes" and "MDN … N/A, no behavior change". The top-level <template shadowrootmode> change affects setHTMLUnsafe() without a sanitizer, which seems worth an MDN issue.
    • "'Appropriate place for inserting a node' consults the map" should say "adjusted insertion location".

Nits

  • source:147154-147160: four lines of the new note are 101–103 columns wide. Running specfmt should fix them.

@noamr

noamr commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author
  • source:147041: using the current node as the declarative shadow host is normative for every fragment parse, not just sanitizing ones. It matches Chrome Canary 157, Fx Nightly 160 and Safari TP (div.setHTMLUnsafe('<template shadowrootmode=open>x</template>y') gives no shadow root and 2 children). Consider mentioning it in the commit message.

Removed this note, it's already the case anyway.

  • PR description:

    • The new "Web-observable changes" list contradicts the checklist, which still says "This mostly keeps existing behavior. The observable difference is coalescing of text nodes" and "MDN … N/A, no behavior change". The top-level <template shadowrootmode> change affects setHTMLUnsafe() without a sanitizer, which seems worth an MDN issue.

Fixed

  • "'Appropriate place for inserting a node' consults the map" should say "adjusted insertion location".

Fixed

Nits

  • source:147154-147160: four lines of the new note are 101–103 columns wide. Running specfmt should fix them.

Fixed

@annevk

annevk commented Oct 13, 2026

Copy link
Copy Markdown
Member
AI feedback

Reviewed at 25ae90c, together with web-platform-tests/wpt#62492. Lint passes and the build succeeds. The issues raised in earlier rounds look fixed at this head: the processing-instruction allow-list, the html/body attribute merges, replaced template, the AAA lastNode and foster-parenting cases, the script/template insertion overrides, and the declarative shadow root registry.

Blockers

  • sanitizer config allows an attribute uses elementName in its navigating-URL and animating-URL steps (L129434, L129444), but never defines it. The algorithm only gets elementLocalName and elementNamespace. As written, the javascript: URL checks can't be evaluated. Adding "Let elementName be «[ "name" → elementLocalName, "namespace" → elementNamespace ]»." after attrName fixes it.

  • insert a foreign element now computes the insertion location before create an element for the token, and inserts at that same location afterwards. In document parsing, creating the element can run script: a microtask checkpoint, a synchronous custom element constructor, or attributeChangedCallback. Main recomputed the location after creation. For example:

    <script>customElements.define("x-foo", class extends HTMLElement {
      constructor() { super(); document.querySelector("table").remove(); } });</script>
    <table><x-foo></x-foo>

    x-foo is foster-parented with location (body, table). The constructor removes the table, so the insertion is before a node that is no longer a child of body, which violates the ensure pre-insert validity assertion. Main appended x-foo to body. Using insertionLocation only for the intended parent, and calling insert an element at the adjusted insertion location with just element as main did, would fix this. The script and template start tag steps follow the same pattern, though there only customized built-ins can run script.

  • The HTML fragment parsing algorithm now creates every parsed element in the inert document, not only top-level ones. This includes innerHTML, insertAdjacentHTML(), createContextualFragment(), and setHTMLUnsafe() without a sanitizer. Some steps resolve a URL against the node document when an attribute is set and don't re-run on adoption: media src (L38973, "when the src attribute was last changed") and poster (L37251). The inert document's base URL is about:blank. So per spec, div.innerHTML = '<p><video src=movie.mp4 poster=p.png></video></p>' no longer loads the video or gets a poster frame. Top-level elements already had this problem on main.

    • The PR description lists the inert creation as intended, but not this fallout.
    • Coherent story for HTML-setting methods #11669 is still open on whether legacy methods should parse into an inert document.
    • Consider limiting the inert fragment document to the parses that need it (non-Legacy mode, or a non-null configuration). Alternatively, first make media src and poster re-run on adoption, which setHTML() and setHTMLUnsafe() need anyway.

Suggestions

  • Consider updating the PR description:
    • The MDN checklist item still says "N/A, no behavior change", which contradicts the "Web-observable changes" list.
    • The list doesn't mention these changes:
      • A declarative shadow root is only attached if the configuration keeps template and its shadowrootmode attribute. template is Uncategorized, so setHTML() with the default configuration no longer creates them; main attached them from the token and sanitized inside. shadowroot* attributes the configuration removes no longer apply either.
      • <template for> patching only happens if the configuration keeps for.
      • Foster-parented text around a replaced table lands after the table's hoisted contents.
      • With body replaced with its children, <frameset> no longer discards the body's content: parseHTMLUnsafe('<span></span><frameset>', {sanitizer: {replaceWithChildrenElements: ["body"]}}) keeps the span.
    • The "root insertion target" was a DocumentFragment-or-null, not a flag.
  • In the adoption agency algorithm's "Keep" case (L148921), newElement is now inserted via insert an element at the adjusted insertion location instead of being appended to furthestBlock. In document parsing, that runs custom element reactions synchronously for newElement and the children just moved into it, e.g., connectedCallback for <b is=x-b> in <b is=x-b><p>x</b>. Main left them on the current element queue. Consider mentioning this in the commit message, or inserting directly at the adjusted insertion location given (furthestBlock, null). The lastNode insertion earlier in the algorithm still uses a plain insert.
  • Consider updating the sanitizer's security considerations. They still say the API "adds a capability to traverse and filter an existing DocumentFragment" (L130554), and describe it as "traversing supplied HTML content" (L130521).
  • Consider correcting the adoption agency algorithm note (L148723). Children of a replaced furthestBlock were inserted wherever furthestBlock would have been inserted, not necessarily into formattingElement. In <b><em><div>Text</b> with div replaced, "Text" is in em.

Nits

  • The parseHTML() domintro (L126661) still says "The resulting document is sanitized"; the other domintros now say the markup is sanitized as it is parsed.
  • "If it is not, add …" (L147594) and "and if it is not, add …" (L147638) need a "then", e.g., "If htmlElement does not have an attribute whose name is attribute's name, then …".
  • "If nodeAction is not "Replace with children", then:" (L148796) doesn't need "then" before a sub-list.
  • "Assert: If" (L146165) → "Assert: if", as elsewhere.
  • "If template has a shadowrootmode attribute and its value is not in the None state" (L147084) → "If template's shadowrootmode attribute is not in the None state". The note between that paragraph and its sub-steps would read better after them.
  • The text-coalescing note (L143007) says "the removed element … will coalesce". It applies to replaced elements too, and notes use the present tense.
  • One of the two blank lines before <h4><dfn>Tokenization</dfn></h4> (L143011) was dropped.
  • In adjusted insertion location (L146078), adjustedInsertionLocation holds the location before adjustment. The map value also doesn't need splitting into two variables only to be returned.
  • sanitizer config allows comments (L129279): one-line algorithms use "…, return …" rather than ": Return …".
  • The template for note (L147215) credits the adjusted insertion location for patching inside templates. The template-contents redirect comes from appropriate place for inserting a node.
  • <dfn>sanitize</dfn> (L127853) now lives in the non-normative introduction, so the normative notes link there. "sanitize the resulting DOM as it is being parsed" also reads oddly.
  • script note (L146988): "not inserted into the document" → "not inserted".
  • The "Replace with children" <dt>s at L146173, L148823, and L148906 wrap mid-span, though they fit in 100 columns.

@annevk

annevk commented Oct 13, 2026

Copy link
Copy Markdown
Member
AI feedback

Reviewed at 53c8837, covering 6624235 and 53c8837 since 25ae90c. Lint passes and the build succeeds. The earlier blockers are addressed. Only sanitizing parses use the inert fragment document now, so innerHTML and other parses without a sanitizer are back to main's behavior. Sanitizing parses still have the regression below.

Blockers

  • Sanitizing parses still break media elements that the configuration keeps.
    • On main, setHTML() and setHTMLUnsafe() parsed into a fragment in the target's document, so nested elements were created there. Now every element of a sanitizing parse is created in the inert document, whose base URL is about:blank.
    • Media src (L38973, "when the src attribute was last changed") and poster (L37251) resolve against the node document when the attribute is set, and don't re-run on adoption.
    • So per spec, div.setHTMLUnsafe('<p><video src=movie.mp4></video></p>', {sanitizer: {}}) no longer loads the video, while the same call without a sanitizer does. This also affects every innerHTML on pages whose Trusted Types default policy returns a sanitizer from createParserOptions.
    • Making media src and poster re-run on adoption, here or in a prerequisite PR, would fix this, as well as the existing top-level case on main.

@noamr

noamr commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

Blockers

  • Sanitizing parses still break media elements that the configuration keeps.

    • On main, setHTML() and setHTMLUnsafe() parsed into a fragment in the target's document, so nested elements were created there. Now every element of a sanitizing parse is created in the inert document, whose base URL is about:blank.
    • Media src (L38973, "when the src attribute was last changed") and poster (L37251) resolve against the node document when the attribute is set, and don't re-run on adoption.
    • So per spec, div.setHTMLUnsafe('<p><video src=movie.mp4></video></p>', {sanitizer: {}}) no longer loads the video, while the same call without a sanitizer does. This also affects every innerHTML on pages whose Trusted Types default policy returns a sanitizer from createParserOptions.
    • Making media src and poster re-run on adoption, here or in a prerequisite PR, would fix this, as well as the existing top-level case on main.

This is an existing issue, I opened #13068, and it's actually something we should fix as part of #798.
The streaming sanitizer reveals it in a new way but the issue exists for e.g. regular fragment parsing already.

@annevk

annevk commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Hmm okay. I thought we had resolved those issues, but I guess there's something lingering just for media elements.

Can you shorten the proposed commit message somewhat?

@noamr

noamr commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Hmm okay. I thought we had resolved those issues, but I guess there's something lingering just for media elements.

Can you shorten the proposed commit message somewhat?

Done (+ rebase, hence the multiple commits)

noamr added 9 commits October 13, 2026 18:06
…s node document

Using the current node (not the adjusted current node) prevents a top-level template in the fragment case from attaching a shadow root to the fragment context element. The declarative shadow root registry now comes from the host's node document, which is the inert document (null registry) when sanitizing.
- Define elementName in 'sanitizer config allows an attribute'.
- Recompute the insertion location after creating an element in 'insert a
  foreign element', and in the script and template start tag steps, since
  creating a customized built-in element can run script. Drop the now-unused
  onlyAddToElementStack parameter.
- Only create the fragment in an inert document when sanitizing; otherwise
  create it in the context's node document as before.
- Use a plain insert for the reconstructed element in the adoption agency
  algorithm, as before.
- Give 'sanitize' a normative definition next to the parser sanitizer
  configuration, and update the security considerations and parseHTML()
  domintro to describe sanitizing while parsing.
- Various wording and formatting nits.
- Look up the custom element registry unconditionally and introduce
  creationRegistry (registry when the sanitizer action is Keep; otherwise
  null) so the call to "create an element" no longer carries an inline
  conditional. Rewrite the note to explain that a null registry is what
  prevents "create an element" from finding a definition.
- Mention processing instructions in the "parser sanitizer configuration"
  prose.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Nodes are made non-inert before sanitizing Streaming sanitizer support

5 participants