Invalidate tokens issued before a password change

Tokens are stateless JWTs, so changing a password left every session that
the old one had opened working until its own expiry, up to a day later.
That is the case the password change is meant to close: an administrator
resetting a compromised account did not evict whoever was already in it.

The auth row already records when the password last changed, so no
migration is needed: `Access.init()` reads it alongside the user it
already loads and refuses a token whose `iat` is older. Both sides are
compared as whole seconds, which is all `iat` carries, so a token minted
in the same second as the change is kept. Postgres stores that column to
the microsecond, which is why the comparison is not done in milliseconds.

It is reported as 401 rather than the usual 403 because that is what the
frontend clears the session on, so the browser holding the dead token
lands on the login page instead of a page full of errors, and `can()`
lets that one error through unwrapped for the same reason.

Only the password does this. A user row changing (a rename, an avatar,
permissions) does not, and a user with no password auth row, which is
what a login through an external provider looks like, is not affected.
This commit is contained in:
José M. Requena Plens
2026-09-06 19:48:02 +02:00
parent a2d427902a
commit 1ffe3609f4
3 changed files with 81 additions and 0 deletions
+43
View File
@@ -31,6 +31,49 @@ describe('Users endpoints', () => {
});
});
it('Should reject a token that was issued before the password changed', () => {
// The token carries whole seconds, so it has to predate the change by one.
cy.wait(1100);
cy.task('backendApiPut', {
token: token,
path: '/api/users/me/auth',
data: {
type: 'password',
current: 'changeme',
secret: 'changeme2'
}
}).then(() => {
cy.task('backendApiGet', {
token: token,
path: '/api/users/me',
returnOnError: true
}).then((data) => {
expect(data).to.have.property('error');
expect(data.error).to.have.property('code');
expect(data.error.code).to.equal(401);
});
// Put the password back, the rest of the suite shares this user, and take a
// token minted after the change: restoring it invalidates the one that made it.
cy.getToken(null, {secret: 'changeme2'}).then((tempToken) => {
cy.task('backendApiPut', {
token: tempToken,
path: '/api/users/me/auth',
data: {
type: 'password',
current: 'changeme2',
secret: 'changeme'
}
}).then(() => {
cy.getToken().then((freshToken) => {
token = freshToken;
});
});
});
});
});
it('Should be able to update yourself', () => {
cy.task('backendApiPut', {
token: token,