Skip to content

🐛 fix(rewrite): apply removals past the depth cap - #2196

Merged
gaborbernat merged 5 commits into
tox-dev:mainfrom
gaborbernat:sec-fix/issue-1758
Nov 15, 2026
Merged

gaborbernat merged 5 commits into
tox-dev:mainfrom
gaborbernat:sec-fix/issue-1758

Conversation

@gaborbernat

@gaborbernat gaborbernat commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

rewrite() could leave markup in the output that a remove() rule should have caught. Past the depth cap the rewriter stopped tracking raw-text elements such as <style>, so the tokenizer read their content as markup, while a browser reads it as text. 🧹 Once this merges, an edit past the cap either applies the way it does below the cap or raises ValueError. Fixes #1758.

The rewriter keeps its own stack of open elements, and the tokenizer's content model has to match what the tree builder does at every depth. Past the cap, a raw-text or RCDATA element takes the one slot the stack keeps, so its content is read as text and its edits apply as they do below the cap. Any other element past the cap is refused, as the tree builder refuses it, and an edit that needs its content raises. The trade-off is that some edits that used to apply partly now raise.

Behavior changes

  • Edits on elements nested past the depth limit, except raw-text elements, raise ValueError instead of applying partly. The edits are remove(), replace(), set_content(), append() and after().
  • A set_content() or append() on a raw-text element past the limit behaves as it does below the limit.
  • A handler on a page with an SVG or MathML element past the limit raises ValueError.
  • The streaming docs state the depth cap as 8,192, the value the code uses.

Past the open-element depth limit a raw-text or RCDATA start tag was not
pushed, so the tokenizer stayed in the data state and read the content
of that element as markup. A script that a remove() rule should catch
could then be hidden inside such content, and the removal never ran.

The tokenizer now takes the content model of a raw-text or RCDATA
element past the limit, as the tree builder does. Edits that need the
content of any other element past the limit raise ValueError, instead
of applying halfway, and a handler that runs while an SVG or MathML
element is past the limit raises as well.

Refs tox-dev#1758
@gaborbernat gaborbernat added the bug Something isn't working label Nov 15, 2026
pre-commit-ci Bot and others added 4 commits November 15, 2026 16:12
A raw-text element that a th_shadow refuses at the tree builder's own cap still
switches the tokenizer, but the spine has no content model for it. Inside an
integration point the spine then treated that raw text as data, so a removed
script's body could leak and raw text was escaped. Past the depth cap the
element's model now comes from the tokenizer state while a th_shadow runs.

Refs tox-dev#1758
Keep the depth test as the first comparison on ordinary input. The
tokenizer state is read only past the cap.
@codspeed

codspeed Bot commented Nov 15, 2026

Copy link
Copy Markdown

Merging this PR will degrade performance by 5.67%

2 warnings

⚠️ 4 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚠️ 4 benchmarks with a significant change ran in a different software environment

Their base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the changes might come from this difference rather than from the code. Open an affected benchmark to see what changed.

See affected benchmarks

⚡ 1 improved benchmark
❌ 3 regressed benchmarks
✅ 578 untouched benchmarks
⏩ 89 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_mutating_feature[path-xpath-one-cold] 107.1 µs 124.9 µs -14.24%
❌ test_feature[query-closest] 256.1 µs 274.2 µs -6.61%
❌ test_feature[text-content] 2.7 ms 2.8 ms -6.12%
⚡ test_feature[select-nth] 462.8 µs 439.4 µs +5.31%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing gaborbernat:sec-fix/issue-1758 (48aad0b) with main (efd4b6a)

Open in CodSpeed

Footnotes

  1. 89 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@gaborbernat
gaborbernat merged commit 3d62ab3 into tox-dev:main Nov 15, 2026
29 of 30 checks passed
gaborbernat added a commit that referenced this pull request Nov 15, 2026
Fixes #1752

`rewrite()` copied text that the tokenizer had gathered from several
source spans. A token dropped between the pieces, such as an empty end
tag or a tag or comment a handler removed, could leave a `<` in front of
a letter, `/`, `!` or `?`. The output then started markup the input did
not have. Such a `<` is now escaped. A `<` or `</` at the end of a run
is still held as the tail that the next write settles.

Past the nesting cap, a raw-text element takes the one slot the spine
keeps (#2196). `rw_data_context` tests only the spine's top entry, so
the escape never changes text inside raw text or RCDATA.

### Behavior changes

- Text that follows a dropped empty end tag, or a removed node, and
starts with a `<` followed by a letter, `/`, `!` or `?` is written with
`&lt;`. The browser reads the same text.
- The docs say so in `docs/how-to/rewriting.rst` and
`docs/explanation/streaming.rst`.

### Merge with #2196

This branch merges `upstream/main` at `3d62ab371`. The past-cap branch
of `rw_handle_element` takes #2196's version. The `untracked_raw` flag
from the first version of this PR is removed, as #2196 suggested. Both
test files merge without conflict, and both pass.

### Tests

- Behavior tests in `tests/tokenizer/test_rewrite.py` fail on the base:
the joined-text cases, the raw-text cases past the cap, and seed 11 of
the seeded property test.
- The seeded property test generates documents and checks that the
element counts of the output do not exceed those of the input, for the
no-handler, script-removal, comment-removal and attribute-edit rewrites.
Removing elements or text can change how a parser builds the tree, so
the property uses handlers that do not remove formatting, table or text
runs.

### Performance

Release LTO builds, callgrind, 20 and 220 repetitions,
`PYTHONHASHSEED=0`, Ir per call. Base is `upstream/main` at `3d62ab371`,
measured on the same build recipe as the head.

| row | main | head | delta |
| --- | ---: | ---: | ---: |
| `rewrite` | 11,238,360 | 11,256,455 | +18,095 (+0.16%) |
| `rewrite-attributes-single` | 3,680 | 3,680 | 0 |
| `parse-xml-text-tiny` (control) | 1,835 | 1,835 | 0 |
| main vs main (noise) | 11,238,360 | 11,238,360 | 0 |

The `rewrite` cost sits in `rw_emit_read_leaf`, in the check that tells
a gathered text run from a slice. Earlier versions of this branch also
had a store on every end tag; the merged tree no longer has it. The
gathered emitter is out of line (`TH_NOINLINE`), which kept the leaf
overhead low. Two optimization rounds were spent on the leaf path before
the merge. The remainder is recorded here.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rewrite() passes a script through a remove() rule after 8192 unclosed tags

1 participant