A test case (CSRFAttackTest) is included to verify that requests are protected against CSRF attacks. In both tests, they attempt to create a Product. If no CSRF token is introduced (a potential attack), request should be rejected. If it is included, Product should be created normally.
This protection should be completely transparent to the user, so all Selenium tests should work as expected with no changes.
For retail tests, AuthenticatedPOSRequestTest were created to allow testing isolated REST requests to a live POS instance. This infrastructure were used to create POSCsrfAttackTest, which is a test similar of what is implemented for the backoffice.
A critical step performance-wise is when processing the POST request body to extract the CSRF Token. Two approaches can be taken to achieve this:
- Parsing the entire response into a JSON Object
- Search the response string using a regular expression.
After comparing the performance of both approaches, the regex is significantly faster than the JSON parse, even more if the response string is large. To make the regex evaluation even faster, the pattern is only compiled the first time it is used and then it is stored for future usages.