Skip to content

fix: anchor keyValuePairsReg to prevent quadratic backtracking#6558

Merged
Eomm merged 3 commits intomainfrom
fix/content-type-regex-backtracking
Mar 7, 2026
Merged

fix: anchor keyValuePairsReg to prevent quadratic backtracking#6558
Eomm merged 3 commits intomainfrom
fix/content-type-regex-backtracking

Conversation

@mcollina
Copy link
Copy Markdown
Member

@mcollina mcollina commented Mar 6, 2026

Summary

  • The content-type parameter regex /([\w!#$%&'*+.^|~-]+)=([^;])/gmexhibited O(N²) backtracking on malformed input (e.g. long strings without=). Adding a (^|;)\s anchor ensures the engine only attempts matches at parameter boundaries (^or;`), reducing worst-case complexity to O(N).
  • Benchmark included in benchmarks/content-type.js — no measurable throughput difference on valid inputs.

Test plan

  • All existing content-type.test.js tests pass
  • Benchmark confirms no performance regression (~4.8M ops/s params, ~12M ops/s basic)
  • Verified O(N) behavior on malicious input up to 16KB (Node.js max header size)

The content-type parameter regex was vulnerable to O(N²) backtracking
on malformed input without `=` characters. Adding a `(^|;)` anchor
ensures the engine only attempts matches at parameter boundaries,
reducing worst-case complexity to O(N) with no measurable impact on
valid input throughput.
Address review feedback: use (?:^|;) non-capture group to keep
original match indices. Remove benchmark file and tinybench dependency.
Co-authored-by: Frazer Smith <[email protected]>
Signed-off-by: Manuel Spigolon <[email protected]>
Copy link
Copy Markdown
Member

@Eomm Eomm left a comment

Choose a reason for hiding this comment

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

Size		Time(ms)	Ratio vs prev
1000		0.1		-
2000		0.0		0.31
5000		0.0		1.86
10000		0.1		2.01
20000		0.1		1.97
50000		0.3		2.47

@Eomm Eomm added the bugfix Issue or PR that should land as semver patch label Mar 7, 2026
@Eomm Eomm merged commit 3b0f769 into main Mar 7, 2026
39 checks passed
@Eomm Eomm deleted the fix/content-type-regex-backtracking branch March 7, 2026 08:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugfix Issue or PR that should land as semver patch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants