session icon indicating copy to clipboard operation
session copied to clipboard

Make sure we set session cookie if saveUninitialized is false and maxAge is on

Open rclmenezes opened this issue 3 years ago • 0 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the bug has not already been reported

Fastify version

4

Plugin version

9

Node.js version

16

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Description

Currently, if maxAge is on and saveUninitialized is false, we don't re-save the session.

See this for original discussion: https://github.com/fastify/session/pull/144#issuecomment-1225872415

Fix is putting the cookie's expiration in the hash:

if (this === sess && key === 'cookie') {
        // we want `touch` to affect the hash of the session
        return sess.cookie.expires?.getTime()
      }
}

Steps to Reproduce

test('should set session cookie if saveUninitialized is false and maxAge is on', async (t) => {
  t.plan(2)
  const options = {
    cookie: {
      maxAge: 42
    },
    secret: 'cNaoPYAwF60HZJzkcNaoPYAwF60HZJzk',
    saveUninitialized: false
  }
  const plugin = fastifyPlugin(async (fastify, opts) => {
    fastify.addHook('onRequest', (request, reply, done) => {
      request.sessionStore.set(DEFAULT_SESSION_ID, {
        // In this scenario, maxAge would have set expires in a previous request
        cookie: {
          expires: new Date(Date.now() + 1000)
        }
      }, done)
    })
  })
  const fastify = await buildFastify((request, reply) => reply.send(200), options, plugin)
  t.teardown(() => fastify.close())

  const response = await fastify.inject({
    url: '/',
    headers: { cookie: DEFAULT_COOKIE, 'x-forwarded-proto': 'https' }
  })

  t.equal(response.statusCode, 200)
  t.ok(response.headers['set-cookie'])
})

Expected Behavior

The session should re-save

rclmenezes avatar Aug 24 '22 18:08 rclmenezes