fix(sessions): keep an ended session's row until it expires

A session renewed from a token issued before sessions were tracked has
an id derived from that token, and the renewal inserts it only when no
row by that id exists. The nightly purge deleted revoked rows straight
away, so the next request with the still valid old token inserted the
session again as an active one and got a fresh tracked token with a new
lifetime. A logout, an ended session or a sign out of the others held
only until the purge ran.

The purge now deletes expired rows only, and a revoked row stays until
its own expiry. A derived row is recorded with an expiry no earlier
than the old token's, so by the time it goes the old token is refused
by its signature check anyway.
This commit is contained in:
Maurice
2026-10-08 17:55:20 +02:00
parent e94525afd3
commit 648f63c626
9 changed files with 104 additions and 24 deletions
+24 -2
View File
@@ -336,7 +336,7 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
expect((await me(there)).status).toBe(401);
}, 15000);
it('the nightly purge removes the ended and expired rows and leaves the live session working', async () => {
it('the nightly purge removes the expired rows, keeps an ended one until it expires, and leaves the live session working', async () => {
const { user, password } = freshUser('sess-purge');
const live = await signIn(user.email, password, 'Live');
const ended = await signIn(user.email, password, 'Ended');
@@ -349,8 +349,30 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
const job = moduleRef.get(SessionPurgeJob);
await withRequestContext(moduleRef.get(MikroORM), () => job.tick());
expect(sessionRows(db as never, user.id).map((row) => row.id)).toEqual([sessionIdOf(live)]);
expect(sessionRows(db as never, user.id).map((row) => row.id).sort()).toEqual([sessionIdOf(live), sessionIdOf(ended)].sort());
expect((await me(live)).status).toBe(200);
expect((await me(ended)).status).toBe(401);
}, 15000);
it('a session renewed from a token from before tracking stays ended through the nightly purge', async () => {
const { user } = freshUser('sess-legacy-purge');
const old = sessionCookie(user.id, 0, { lifetime: 86400, consumed: 60000 });
const first = await request(server).get('/api/auth/me').set('Cookie', old).set('User-Agent', 'Old');
const renewedCookie = ((first.headers['set-cookie'] ?? []) as unknown as string[]).find((c) => c.startsWith('trek_session='))!;
const renewed = /^(trek_session=[^;]+)/.exec(renewedCookie)![1];
expect((await request(server).post('/api/auth/logout').set('Cookie', renewed)).status).toBe(200);
expect((await me(renewed)).status).toBe(401);
const job = moduleRef.get(SessionPurgeJob);
await withRequestContext(moduleRef.get(MikroORM), () => job.tick());
// The old token itself lives out its own expiry, but it is not renewed into the ended session again.
const again = await request(server).get('/api/auth/me').set('Cookie', old).set('User-Agent', 'Old');
expect(again.status).toBe(200);
expect(((again.headers['set-cookie'] ?? []) as unknown as string[]).some((c) => c.startsWith('trek_session='))).toBe(false);
expect(sessionRows(db as never, user.id)).toEqual([expect.objectContaining({ id: sessionIdOf(renewed), revoked_at: expect.any(String) })]);
const list = await request(server).get('/api/auth/sessions').set('Cookie', old);
expect(list.body.sessions).toEqual([]);
}, 15000);
});
@@ -127,17 +127,20 @@ describe('UserSessionsRepository', () => {
expect(row('theirs')).toEqual(expect.objectContaining({ revoked_at: null }));
});
it('SESSREPO-008: deleteInactive removes the expired and the revoked rows and keeps the live ones', async () => {
it('SESSREPO-008: deleteInactive removes the expired rows, revoked or not, and keeps the rest', async () => {
const { user } = createUser(testDb);
await add('live', user.id);
await add('expired', user.id, { expires_at: NOW });
await add('revoked', user.id);
testDb.prepare("UPDATE user_sessions SET revoked_at = ? WHERE id = 'revoked'").run(EARLIER);
await add('revoked-expired', user.id, { expires_at: EARLIER });
testDb.prepare("UPDATE user_sessions SET revoked_at = ? WHERE id IN ('revoked', 'revoked-expired')").run(EARLIER);
expect(await sessions.deleteInactive(NOW)).toBe(2);
expect(row('live')).toBeDefined();
expect(row('expired')).toBeUndefined();
expect(row('revoked')).toBeUndefined();
expect(row('revoked-expired')).toBeUndefined();
// Revoked but not yet expired: kept, it still refuses the token it was derived from.
expect(row('revoked')).toEqual(expect.objectContaining({ revoked_at: EARLIER }));
});
it('SESSREPO-009: the rows go with their user', async () => {
@@ -34,7 +34,7 @@ describe('SessionPurgeJob', () => {
const now = new Date('2026-10-08T03:45:00.000Z');
await make(purge).job.tick(now);
expect(purge).toHaveBeenCalledWith(now);
expect(logMock.logInfo).toHaveBeenCalledWith('Session purge: removed 3 expired or revoked session(s)');
expect(logMock.logInfo).toHaveBeenCalledWith('Session purge: removed 3 expired session(s)');
});
it('SESSPURGE-003: stays quiet when there was nothing to purge', async () => {
@@ -173,6 +173,34 @@ describe('SessionsService.renew of a token from before tracking', () => {
expect(testDb.prepare('SELECT COUNT(*) AS n FROM user_sessions WHERE user_id = ?').get(user.id)).toEqual({ n: 1 });
});
it('SESS-017: a session derived from it that was ended stays ended through the nightly purge', async () => {
const { user } = createUser(testDb);
const legacy = untracked(user.id);
const first = claimsOf((await svc.renew({ id: user.id, pv: 0, token: legacy }))!);
expect(await svc.revoke(user.id, first.jti)).toBe(true);
// The purge that night, while the old token is still valid.
expect(await svc.purgeInactive(new Date())).toBe(0);
expect(await svc.renew({ id: user.id, pv: 0, token: legacy })).toBeNull();
expect(rowOf(first.jti)?.revoked_at).not.toBeNull();
expect(await svc.list(user.id)).toEqual([]);
// Once the old token has expired the row may go, since the token is refused by then.
const legacyExp = (jwt.decode(legacy) as { exp: number }).exp;
expect(await svc.purgeInactive(new Date((legacyExp + SESSION_DURATION_SECONDS + 60) * 1000))).toBe(1);
expect(() => jwt.verify(legacy, JWT_SECRET, { algorithms: ['HS256'], clockTimestamp: legacyExp + 60 })).toThrow();
});
it('SESS-018: the derived session is kept at least as long as the old token lives', async () => {
const { user } = createUser(testDb);
// An old token with a longer life than the one it is renewed into.
const legacy = jwt.sign({ id: user.id, pv: 0 }, JWT_SECRET, { algorithm: 'HS256', expiresIn: SESSION_DURATION_REMEMBER_SECONDS });
const renewed = claimsOf((await svc.renew({ id: user.id, pv: 0, token: legacy }))!);
expect(renewed.exp - renewed.iat).toBe(SESSION_DURATION_SECONDS);
expect(rowOf(renewed.jti)?.expires_at).toBe(textOf((jwt.decode(legacy) as { exp: number }).exp));
});
it('SESS-014: two different tokens of the same user stay two sessions', async () => {
const { user } = createUser(testDb);
const a = claimsOf((await svc.renew({ id: user.id, pv: 0, token: untracked(user.id) }))!);
@@ -244,19 +272,23 @@ describe('SessionsService list and revoke', () => {
expect(rowOf(mine.jti)?.revoked_at).not.toBeNull();
});
it('SESS-011: purgeInactive removes the expired and revoked rows', async () => {
it('SESS-011: purgeInactive removes the expired rows and keeps a revoked one until it expires', async () => {
const { user } = createUser(testDb);
const live = claimsOf(await svc.issue({ id: user.id, pv: 0 }, true));
const ended = claimsOf(await svc.issue({ id: user.id, pv: 0 }, true));
const short = claimsOf(await svc.issue({ id: user.id, pv: 0 }, false));
await svc.revoke(user.id, ended.jti);
// Just past the default lifetime: the short session has expired, the remembered one has not.
// Just past the default lifetime: the short session has expired, the remembered ones have not.
expect(SESSION_DURATION_REMEMBER_SECONDS).toBeGreaterThan(SESSION_DURATION_SECONDS + 60);
expect(await svc.purgeInactive(new Date(Date.now() + (SESSION_DURATION_SECONDS + 60) * 1000))).toBe(2);
expect(await svc.purgeInactive(new Date(Date.now() + (SESSION_DURATION_SECONDS + 60) * 1000))).toBe(1);
expect(rowOf(live.jti)).toBeDefined();
expect(rowOf(ended.jti)).toBeUndefined();
expect(rowOf(ended.jti)?.revoked_at).not.toBeNull();
expect(rowOf(short.jti)).toBeUndefined();
// Past the long lifetime as well: the revoked row goes with the live one.
expect(await svc.purgeInactive(new Date(Date.now() + (SESSION_DURATION_REMEMBER_SECONDS + 60) * 1000))).toBe(2);
expect(rowOf(ended.jti)).toBeUndefined();
});
});