Skip to content

fix: reset lastIndex before testing global/sticky content-type RegExp parsers - #6846

Merged
climba03003 merged 1 commit into
fastify:mainfrom
zelinewang:fix/content-type-parser-stateful-regexp
Aug 8, 2026
Merged

climba03003 merged 1 commit into
fastify:mainfrom
zelinewang:fix/content-type-parser-stateful-regexp

Conversation

@zelinewang

Copy link
Copy Markdown
Contributor

Checklist

What this does

ContentTypeParser.getParser walks parserRegExpList and calls parserRegExp.test(ct) to find a matching custom parser. When a parser is registered with a RegExp that carries the g or y flag, RegExp.prototype.test is stateful: it advances lastIndex on a match and resumes from there on the next call. So the same parser RegExp can match one request and then miss (or partially match) a later one for the same content type, depending on where lastIndex was left.

The fix resets parserRegExp.lastIndex = 0 before each test(), which makes matching independent of previous calls. Parsers registered with non-global RegExps (the common case) are unaffected, since lastIndex is not used there.

Added a regression test that registers a global-flagged content-type RegExp and sends two matching requests; it fails before this change (the second request misses the parser) and passes after.

… parsers

A content-type parser registered with a g- or y-flagged RegExp keeps a mutable
lastIndex between calls, so getParser's .test() could skip part of the next
content type and match inconsistently. Reset lastIndex before each test.

@climba03003 climba03003 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.

The fixes LGTM.

But I do not think both g and y flag should be used in Content-Type matching.

@zelinewang

Copy link
Copy Markdown
Contributor Author

yeah fair, those flags come from user regexps tho, fastify never sets them itself. happy to just strip g/y at registration instead if you prefer that over resetting lastIndex

@mcollina mcollina 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.

lgtm

@Eomm

Eomm commented Jul 15, 2026

Copy link
Copy Markdown
Member

The fixes LGTM.

But I do not think both g and y flag should be used in Content-Type matching.

We may check the regex.flags.includes('g') and print a warning?

Independently by the fix, (maybe) we are changing the dev's intentions

@climba03003
climba03003 merged commit 16a74e7 into fastify:main Aug 8, 2026
36 checks passed
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.

4 participants

Sponsor
SponsoredKunjungi sekarang
Promo