Query randomly errors with Unauthorized for certain simple query

Indeed it does not provide much. Which server and driver versions are you using? Usually we get the database name and the operation.

There is no reasons for such a behaviour. I suspect that your variable db is changed by some other functions. At this point I would catch the error and add some tracing so that you can confirm that db is not changed and that the client has not been re-authenticated with some other credentials.