Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fastify Csrf Protection with @fastify/session plugin #961

Open
theBGuy opened this issue Nov 13, 2023 · 0 comments
Open

Fastify Csrf Protection with @fastify/session plugin #961

theBGuy opened this issue Nov 13, 2023 · 0 comments

Comments

@theBGuy
Copy link

theBGuy commented Nov 13, 2023

You have already researched for similar issues?

Yes, I have also reached out multiple times on the fastify discord.

What are you trying to achieve, or the steps to reproduce?

I am attempting to use the csrf-protection plugin in my application. The issue I am having is with the internal csrfProtection function. Included here https://github.com/fastify/csrf-protection/blob/43c02f4223edaa2c1ef934cbb51026e0b29063cb/index.js#L113 I added a couple logging statements.

function csrfProtection (req, reply, next) {
    const secret = getSecret(req, reply)
    if (!secret) {
      req.log.warn('Missing csrf secret')
      return reply.send(new MissingCSRFSecretError())
    }
    if (!tokens.verify(secret, getToken(req), getUserInfo(req))) {
      req.log.warn('Invalid csrf token')
      req.log.warn({ token: getToken(req), secret: secret, userInfo: getUserInfo(req) });
      req.log.info(`Verify: ${tokens.verify(secret, getToken(req), getUserInfo(req))}`);
      return reply.send(new InvalidCSRFTokenError())
    }
    next()
  }

I can confirm that the value from getToken and the secret from getSecret are exactly the same. However it is still failing the verify method. I am not sure what I am missing. Here is my test route,

fastify.post('/test', {
    onRequest: fastify.csrfProtection,
    // onRequest: function (request, reply, done) {
    //   const csrf = request.unsignCookie(request.cookies['xsrf]);
    //   if (!request.session.user) {
    //     reply.code(403).send({ error: 'Unauthorized' });
    //   } else if (!csrf.valid || csrf.value !== request.session._csrf) {
    //     reply.code(403).send({ error: 'Invalid CSRF token' });
    //   } else {
    //     done();
    //   }
    // },
  }, async function (request, reply) {
    return { message: 'Hello world' };
  });

The commented out method works, but the decorated method doesn't

Context

  • node version: 20
  • fastify version: >=4.24.3
  • @fastify/csrf-protection: ^6.3.0
  • @fastify/session: ^10.5.0
  • @fastify/cooki: ^9.1.0
  • os: Windows
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

No branches or pull requests

1 participant