Skip to content

avoid quadratic trailing-punctuation scan in urlize#2204

Closed
zayeem06 wants to merge 1 commit into
pallets:mainfrom
zayeem06:urlize-trailing-scan
Closed

avoid quadratic trailing-punctuation scan in urlize#2204
zayeem06 wants to merge 1 commit into
pallets:mainfrom
zayeem06:urlize-trailing-scan

Conversation

@zayeem06

@zayeem06 zayeem06 commented Jul 1, 2026

Copy link
Copy Markdown

urlize strips trailing punctuation from each word with an unanchored re.search(r"([)>.,\n]|>)+\$", middle), which retries the greedy match from every position. When a word is a long run of those characters (a typed > is escaped to > first) followed by one non-matching character, the search runs in quadratic time, so a ~32 KB value passed through the filter stalls a single render for ~12s while linkifying otherwise harmless text. This replaces the suffix search with a backward scan that trims the same characters plus the > entity in linear time, so the output is identical but the work is O(n).

I added a test covering trailing >/entity stripping so the behavior is pinned, and the existing urlize tests plus the rest of the suite still pass. Worth verifying the scan handles the > boundary the same way the old alternation did, which the new test exercises.

@davidism davidism closed this Jul 2, 2026
@zayeem06

zayeem06 commented Jul 3, 2026

Copy link
Copy Markdown
Author

All good if this isn't something worth taking on. Leaving the context here in case it's useful: the slow input is an untrusted value passed to |urlize, not template source, and around 32 KB of > characters stalls a single render for ~12s under autoescape, since the escaped > run hits the unanchored suffix search from every position. I've got a small reproducer if that helps. If you'd rather see this as a security report than a PR, I'm happy to send it that way instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants