An email regex that freezes a server
This email regex looks fine, but one bad input can freeze a Node server for 10 seconds: /^(\w+\.?)+@\w+\.\w+$/
Here is the problem, step by step.
1. What it means \w+ is "1 or more letters". \.? is "maybe a dot". The ( )+ around them means "repeat this group". So "anna.smith" is read as 2 groups: "anna." and "smith".
2. Where it goes wrong Without dots, the same letters can be cut into groups in many ways. "aaaa" can be 1 group (aaaa), 2 groups (a|aaa, aa|aa, aaa|a), 3 groups (a|a|aa, a|aa|a, aa|a|a) or 4 groups (a|a|a|a). That's 8 ways.
3. The bad input Type "aaaa!" into the email field. There is no @, so the match fails at the "!". The engine doesn't know that the way it split the letters can't fix that, so it goes back and tries all 8 splits before it says no.
4. Why it explodes Each extra letter doubles the number of ways. 20 a's: 524,288 ways, 0.001 s 28 a's: 134 million ways, 0.3 s 33 a's: 4.3 billion ways, 10.5 s
5. Why the whole server stops Node runs your JavaScript on 1 thread. While it was checking that one email, a request from another user waited 10.5 seconds too.
The fix is one + instead of a + inside a +. Put the dot in the same set as the letters, and there is only 1 way to read them: /^[\w.]+@\w+\.\w+$/ Same input: 0.002 ms.
This kind of bug is called ReDoS. Backtracking like this took Cloudflare down for 27 minutes in 2019.