google/sqlcommenter

Express middleware can write the wrong route

aabmass opened this issue · 0 comments

This effects both sequelize and knex as they use the same mechanism. The middleware sets the current request on the global Knex object:

Knex.__middleware__ = true;
Knex.__req__ = req;

And then uses this request in the wrapped query function to get route information

const req = Knex.__req__;
comments['route'] = req.path;

However, if the middleware runs again for a different concurrent request to a different route before the actual handler does the querying, it will overwrite Knex.__req__ with the new request. This can happen if the handler yields the event loop before it queries.

E.g. request comes for /foo and while it awaits something(), a request comes for /bar causing the middleware to overwrite __req__. Then /foo runs knex.select() and the query is annotated with the wrong request:

app.get('/foo', async (req, res) => {
  await something();
  const records = await knex.select(...);
  res.json(records);
});

app.get('/bar', async (req, res) => {
  const records = await knex.select(...);
  res.json(records);
});