From 035bc4a8aa8a9687618b9a4eb18eaf3d20fd3375 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Fri, 4 Dec 2026 22:33:20 -0500 Subject: [PATCH 1/2] fix(sessions): enforce the concurrent session limit on sign-in age, atomically Eviction ordered by row creation, which a refresh resets, so a session that refreshed often was never evicted. It now orders by when the sign-in started, evicts with an update conditional on the row still being the chain head (following a rotation to its replacement), and holds a per-user advisory lock across count, evict and create. --- .changeset/concurrent-session-cap.md | 5 + src/services/concurrentSessionPolicy.ts | 229 +++++++++++++----- src/services/sessionIssuance.ts | 22 +- tests/postgres/concurrentSessionLimit.spec.ts | 101 ++++++++ .../services/concurrentSessionPolicy.spec.ts | 203 +++++++++++++--- .../unit/services/sessionIssueService.spec.ts | 32 ++- 6 files changed, 480 insertions(+), 112 deletions(-) create mode 100644 .changeset/concurrent-session-cap.md create mode 100644 tests/postgres/concurrentSessionLimit.spec.ts diff --git a/.changeset/concurrent-session-cap.md b/.changeset/concurrent-session-cap.md new file mode 100644 index 00000000..43ad2950 --- /dev/null +++ b/.changeset/concurrent-session-cap.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +The concurrent session limit (`max_concurrent_sessions`) now evicts the sign-in that started first, rather than the session row created first. A refresh writes a new row, so a session that refreshed often used to look newest and was never the one evicted. Eviction is now conditional on the row still being the head of its chain, and follows a refresh that rotated it so the replacement is evicted instead. Counting, evicting and creating a session now hold a per-user lock, so parallel sign-ins can no longer each count the same sessions and leave the user above the limit. With no limit configured, nothing is locked. diff --git a/src/services/concurrentSessionPolicy.ts b/src/services/concurrentSessionPolicy.ts index 15e02eda..a6d4bcb1 100644 --- a/src/services/concurrentSessionPolicy.ts +++ b/src/services/concurrentSessionPolicy.ts @@ -5,7 +5,7 @@ */ import { Request } from 'express'; -import { Op } from 'sequelize'; +import { literal, Op, QueryTypes, type Transaction } from 'sequelize'; import { Session } from '../models/sessions.js'; import getLogger from '../utils/logger.js'; @@ -17,13 +17,131 @@ const logger = getLogger('concurrentSessionPolicy'); /** The reason written to `sessions.revokedReason`, so an audit can tell why it ended. */ export const EVICTION_REASON = 'concurrent_session_limit'; +const SESSION_SLOT_LOCK_CLASS = 72_641_004; +const MAX_CHAIN_STEPS = 10_000; + +interface LimitParams { + userId: string; + limit: number | null | undefined; + req: Request; + now?: Date; +} + +interface Evictions { + evicted: Session[]; + activeBefore: number; +} + +const NONE: Evictions = { evicted: [], activeBefore: 0 }; + +function inTransaction(transaction?: Transaction) { + return transaction ? { transaction } : {}; +} + /** - * Makes room for one more session by revoking the oldest, when a user is at the - * configured limit. + * Revokes the sign-in `session` heads, following it forward when a refresh rotated it + * after it was read. The update is conditional on the row still being the head, so a + * refresh cannot slip a live replacement past it. Returns the row that was revoked, or + * null when the chain had already ended. + */ +async function evictChain(session: Session, now: Date, transaction?: Transaction) { + let current: Session | null = session; + + for (let steps = 0; current && steps < MAX_CHAIN_STEPS; steps++) { + const [revoked] = await Session.update( + { revokedAt: now, revokedReason: EVICTION_REASON }, + { + where: { id: current.id, revokedAt: null, replacedBySessionId: null }, + ...inTransaction(transaction), + }, + ); + + if (revoked === 1) return current; + + const latest: Session | null = await Session.findByPk(current.id, inTransaction(transaction)); + if (!latest || latest.revokedAt || !latest.replacedBySessionId) return null; + + current = await Session.findByPk(latest.replacedBySessionId, inTransaction(transaction)); + } + + return null; +} + +/** + * Revokes the oldest sign-ins until one more fits under the limit. Throws on a database + * error, leaving the caller to decide whether the sign-in goes on. * - * Called before the new session is created, so the limit counts what will exist - * once it is: at a limit of 3, a user holding 3 loses their oldest and ends up - * with 3 again rather than 4. + * Oldest means the sign-in that started first. A refresh writes a new row, so ordering by + * the row would let a session that refreshes often stay newest forever. + * + * An exchanged session does not count and is never evicted here. It ends with its parent, so + * the parent is what the limit counts, and evicting the parent to make room for its own child + * would end both. + */ +async function evictSurplus( + userId: string, + limit: number, + now: Date, + transaction?: Transaction, +): Promise { + const active = await Session.findAll({ + where: { + userId, + revokedAt: null, + replacedBySessionId: null, + parentSessionId: null, + expiresAt: { [Op.gt]: now }, + }, + order: [ + [literal('COALESCE("chainStartedAt", "createdAt")'), 'ASC'], + ['createdAt', 'ASC'], + ], + ...inTransaction(transaction), + }); + + // The incoming session is not stored yet, so the limit is compared against + // what is already there plus the one about to be added. + const surplus = active.length + 1 - limit; + const evicted: Session[] = []; + + for (const session of active.slice(0, Math.max(surplus, 0))) { + const revoked = await evictChain(session, now, transaction); + if (revoked) evicted.push(revoked); + } + + return { evicted, activeBefore: active.length }; +} + +// After the evictions are committed, so the cascade reads them as ended. +async function recordEvictions({ evicted, activeBefore }: Evictions, params: LimitParams) { + for (const session of evicted) { + await revokeOrphanedChildSessions(session); + + await AuthEventService.log({ + userId: params.userId, + type: 'session_evicted', + req: params.req, + metadata: { + reason: 'Concurrent session limit reached', + sessionId: session.id, + limit: params.limit, + activeBefore, + }, + }); + } + + if (evicted.length > 0) { + logger.info( + `Evicted ${evicted.length} session(s) to stay within the limit of ${params.limit}.`, + ); + } +} + +/** + * Makes room for one more session by revoking the oldest, when a user is at the + * configured limit, at a limit of 3 leaving a user who holds 3 with 2 before the new one is + * created. Sign-ins go through {@link withConcurrentSessionSlot}, which serialises this with + * the create that follows. * * Revoking rather than refusing is deliberate. A refusal locks a user out of the * device in front of them until something they may not have access to expires, @@ -33,72 +151,69 @@ export const EVICTION_REASON = 'concurrent_session_limit'; * leaves users above it, and they should converge on the next sign-in rather * than one session per login forever. * - * An exchanged session does not count and is never evicted here. It ends with its parent, so - * the parent is what the limit counts, and evicting the parent to make room for its own child - * would end both. - * * Never throws. A session that could not be revoked is logged and the sign-in * continues, because failing an authentication over a housekeeping step is worse * than briefly exceeding the cap. */ -export async function enforceConcurrentSessionLimit(params: { - userId: string; - limit: number | null | undefined; - req: Request; - now?: Date; -}): Promise { - const { userId, limit, req } = params; +export async function enforceConcurrentSessionLimit(params: LimitParams): Promise { + const { userId, limit } = params; if (!limit || limit < 1) { return 0; } - const now = params.now ?? new Date(); + let outcome = NONE; try { - const active = await Session.findAll({ - where: { - userId, - revokedAt: null, - replacedBySessionId: null, - parentSessionId: null, - expiresAt: { [Op.gt]: now }, - }, - order: [['createdAt', 'ASC']], - }); + outcome = await evictSurplus(userId, limit, params.now ?? new Date()); + } catch (error) { + logger.error(`Could not enforce the concurrent session limit: ${error}`); + } - // The incoming session is not stored yet, so the limit is compared against - // what is already there plus the one about to be added. - const surplus = active.length + 1 - limit; + await recordEvictions(outcome, params); + return outcome.evicted.length; +} - if (surplus < 1) { - return 0; - } +/** + * Runs `create` with room made for it under the user's concurrent session limit. + * + * Counting, evicting and creating hold a per-user transaction lock, so two sign-ins for the + * same user cannot both count the same sessions and each add one. The eviction runs in a + * savepoint, so one that fails is rolled back and logged and the create still goes ahead. + * With no limit configured nothing is locked and `create` runs on its own. + */ +export async function withConcurrentSessionSlot( + params: LimitParams, + create: (transaction?: Transaction) => Promise, +): Promise { + const { userId, limit } = params; + + if (!limit || limit < 1) { + return create(); + } + + const sequelize = Session.sequelize!; + const now = params.now ?? new Date(); + let outcome = NONE; + + const created = await sequelize.transaction(async (transaction) => { + await sequelize.query('SELECT pg_advisory_xact_lock(:lockClass, hashtext(:userId))', { + replacements: { lockClass: SESSION_SLOT_LOCK_CLASS, userId }, + type: QueryTypes.SELECT, + transaction, + }); - const evicted = active.slice(0, surplus); - - for (const session of evicted) { - await session.update({ revokedAt: now, revokedReason: EVICTION_REASON }); - await revokeOrphanedChildSessions(session); - - await AuthEventService.log({ - userId, - type: 'session_evicted', - req, - metadata: { - reason: 'Concurrent session limit reached', - sessionId: session.id, - limit, - activeBefore: active.length, - }, - }); + try { + outcome = await sequelize.transaction({ transaction }, (savepoint) => + evictSurplus(userId, limit, now, savepoint), + ); + } catch (error) { + logger.error(`Could not enforce the concurrent session limit: ${error}`); } - logger.info(`Evicted ${evicted.length} session(s) to stay within the limit of ${limit}.`); + return create(transaction); + }); - return evicted.length; - } catch (error) { - logger.error(`Could not enforce the concurrent session limit: ${error}`); - return 0; - } + await recordEvictions(outcome, params); + return created; } diff --git a/src/services/sessionIssuance.ts b/src/services/sessionIssuance.ts index 4fe18c2e..9c3ce529 100644 --- a/src/services/sessionIssuance.ts +++ b/src/services/sessionIssuance.ts @@ -13,7 +13,7 @@ import { Session, SessionAuthMethod } from '../models/sessions.js'; import { computeSessionTimes, parseDurationToSeconds } from '../utils/utils.js'; import { mintAccessToken } from './accessTokenService.js'; import { AuthEventService } from './authEventService.js'; -import { enforceConcurrentSessionLimit } from './concurrentSessionPolicy.js'; +import { withConcurrentSessionSlot } from './concurrentSessionPolicy.js'; import { type HookClaims, type LoginHookContext, @@ -183,18 +183,11 @@ export async function issueSessionAndRespond(params: IssueSessionParams): Promis now, ); - // Before the row exists, so the limit counts the session about to be created. - await enforceConcurrentSessionLimit({ - userId: user.id, - limit: max_concurrent_sessions, - req, - }); - - const session = await Session.create({ + const attributes = { userId: user.id, infraId: process.env.APP_ID!, organizationId, - mode: 'server', + mode: 'server' as const, refreshTokenLookup, userAgent: req.get('user-agent'), ipAddress: req.ip, @@ -206,7 +199,14 @@ export async function issueSessionAndRespond(params: IssueSessionParams): Promis authMethods: recordAuthMethod(method, now, passkey), authTime: now, hookClaims, - }); + }; + + // Room is made before the row exists, so the limit counts the session about to be created. + const session = await withConcurrentSessionSlot( + { userId: user.id, limit: max_concurrent_sessions, req }, + (transaction) => + transaction ? Session.create(attributes, { transaction }) : Session.create(attributes), + ); const { token } = await mintAccessToken({ session: { id: session.id, organizationId, recovery, hookClaims }, diff --git a/tests/postgres/concurrentSessionLimit.spec.ts b/tests/postgres/concurrentSessionLimit.spec.ts new file mode 100644 index 00000000..9f87ce41 --- /dev/null +++ b/tests/postgres/concurrentSessionLimit.spec.ts @@ -0,0 +1,101 @@ +import { randomUUID } from 'crypto'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { + enforceConcurrentSessionLimit, + EVICTION_REASON, + withConcurrentSessionSlot, +} from '../../src/services/concurrentSessionPolicy.js'; +import { claimSessionRotation } from '../../src/services/sessionService.js'; + +type Models = Awaited>; + +let Session: Models['Session']; +let User: Models['User']; + +const req = { ip: '127.0.0.1', headers: {}, get: () => undefined } as never; + +async function createUser() { + const id = randomUUID(); + await User.create({ id, email: `limit-${id}@example.com`, phone: null }); + return id; +} + +function sessionAttributes(userId: string, chainStartedAt: Date) { + const now = Date.now(); + return { + userId, + mode: 'server' as const, + refreshTokenLookup: randomUUID(), + expiresAt: new Date(now + 3_600_000), + idleExpiresAt: new Date(now + 3_600_000), + lastUsedAt: new Date(now), + chainStartedAt, + }; +} + +async function liveHeads(userId: string) { + return Session.findAll({ where: { userId, revokedAt: null, replacedBySessionId: null } }); +} + +beforeAll(async () => { + ({ Session, User } = await initializeModels()); +}); + +afterAll(async () => { + await getSequelize().close(); +}); + +describe('the concurrent session limit', () => { + it('evicts the sign-in that started first, however recently it refreshed', async () => { + const userId = await createUser(); + const started = new Date(Date.now() - 60_000); + const first = await Session.create(sessionAttributes(userId, started)); + const second = await Session.create(sessionAttributes(userId, new Date(Date.now() - 30_000))); + // The first sign-in refreshes, so its head is now the newest row. + const firstNext = await Session.create(sessionAttributes(userId, started)); + await claimSessionRotation(first, firstNext.id); + + const evicted = await enforceConcurrentSessionLimit({ userId, limit: 2, req }); + + expect(evicted).toBe(1); + await firstNext.reload(); + expect(firstNext.revokedReason).toBe(EVICTION_REASON); + await second.reload(); + expect(second.revokedAt).toBeNull(); + }); + + it('lets parallel sign-ins at the limit leave only the limit live', async () => { + const userId = await createUser(); + await Session.create(sessionAttributes(userId, new Date(Date.now() - 60_000))); + + await Promise.all( + Array.from({ length: 4 }, () => + withConcurrentSessionSlot({ userId, limit: 1, req }, (transaction) => + Session.create(sessionAttributes(userId, new Date()), { transaction }), + ), + ), + ); + + expect(await liveHeads(userId)).toHaveLength(1); + }); + + it('evicts the replacement when a refresh rotates the oldest mid-eviction', async () => { + const userId = await createUser(); + const started = new Date(Date.now() - 60_000); + const oldest = await Session.create(sessionAttributes(userId, started)); + const replacement = await Session.create(sessionAttributes(userId, started)); + + await Promise.all([ + claimSessionRotation(oldest, replacement.id), + withConcurrentSessionSlot({ userId, limit: 1, req }, (transaction) => + Session.create(sessionAttributes(userId, new Date()), { transaction }), + ), + ]); + + const heads = await liveHeads(userId); + expect(heads).toHaveLength(1); + expect(heads[0].id).not.toBe(replacement.id); + }); +}); diff --git a/tests/unit/services/concurrentSessionPolicy.spec.ts b/tests/unit/services/concurrentSessionPolicy.spec.ts index a0c272cd..2992e82b 100644 --- a/tests/unit/services/concurrentSessionPolicy.spec.ts +++ b/tests/unit/services/concurrentSessionPolicy.spec.ts @@ -1,24 +1,30 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { literal, Op } from 'sequelize'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { Session } from '../../../src/models/sessions.js'; import { AuthEventService } from '../../../src/services/authEventService.js'; import { - EVICTION_REASON, enforceConcurrentSessionLimit, + EVICTION_REASON, + withConcurrentSessionSlot, } from '../../../src/services/concurrentSessionPolicy.js'; +import { revokeOrphanedChildSessions } from '../../../src/services/sessionService.js'; const NOW = new Date('2026-08-30T12:00:00.000Z'); -function buildActiveSession(id: string) { - return { id, update: vi.fn().mockResolvedValue(undefined) }; -} - function req() { return { ip: '127.0.0.1', headers: {}, get: () => undefined } as never; } +function evictedIds() { + return (Session.update as any).mock.calls + .filter(([values]: any[]) => values.revokedReason === EVICTION_REASON) + .map(([, options]: any[]) => options.where.id); +} + beforeEach(() => { (Session.findAll as any).mockResolvedValue([]); + (Session.update as any).mockResolvedValue([1]); }); describe('when no limit is configured', () => { @@ -48,7 +54,7 @@ describe('when no limit is configured', () => { describe('when the user is below the limit', () => { it('leaves existing sessions alone', async () => { - (Session.findAll as any).mockResolvedValue([buildActiveSession('s-1')]); + (Session.findAll as any).mockResolvedValue([{ id: 's-1' }]); const evicted = await enforceConcurrentSessionLimit({ userId: 'user-1', @@ -58,15 +64,14 @@ describe('when the user is below the limit', () => { }); expect(evicted).toBe(0); + expect(Session.update).not.toHaveBeenCalled(); expect(AuthEventService.log).not.toHaveBeenCalled(); }); }); describe('when the user is at the limit', () => { - it('revokes the oldest to make room for the new session', async () => { - const oldest = buildActiveSession('s-oldest'); - const newer = buildActiveSession('s-newer'); - (Session.findAll as any).mockResolvedValue([oldest, newer]); + it('revokes the oldest head, conditionally, to make room for the new session', async () => { + (Session.findAll as any).mockResolvedValue([{ id: 's-oldest' }, { id: 's-newer' }]); const evicted = await enforceConcurrentSessionLimit({ userId: 'user-1', @@ -76,32 +81,38 @@ describe('when the user is at the limit', () => { }); expect(evicted).toBe(1); - expect(oldest.update).toHaveBeenCalledWith({ - revokedAt: NOW, - revokedReason: EVICTION_REASON, - }); - expect(newer.update).not.toHaveBeenCalled(); + expect(Session.update).toHaveBeenCalledTimes(1); + expect(Session.update).toHaveBeenCalledWith( + { revokedAt: NOW, revokedReason: EVICTION_REASON }, + { where: { id: 's-oldest', revokedAt: null, replacedBySessionId: null } }, + ); + expect(revokeOrphanedChildSessions).toHaveBeenCalledWith({ id: 's-oldest' }); }); - it('asks for active sessions oldest first', async () => { - (Session.findAll as any).mockResolvedValue([buildActiveSession('s-1')]); + // A refresh writes a new row, so ordering by the row let a session that refreshes + // often stay newest forever. + it('asks for active sessions by when their sign-in started', async () => { + (Session.findAll as any).mockResolvedValue([{ id: 's-1' }]); await enforceConcurrentSessionLimit({ userId: 'user-1', limit: 1, req: req(), now: NOW }); - expect(Session.findAll).toHaveBeenCalledWith( - expect.objectContaining({ - where: expect.objectContaining({ - userId: 'user-1', - revokedAt: null, - replacedBySessionId: null, - }), - order: [['createdAt', 'ASC']], - }), - ); + expect(Session.findAll).toHaveBeenCalledWith({ + where: { + userId: 'user-1', + revokedAt: null, + replacedBySessionId: null, + parentSessionId: null, + expiresAt: { [Op.gt]: NOW }, + }, + order: [ + [literal('COALESCE("chainStartedAt", "createdAt")'), 'ASC'], + ['createdAt', 'ASC'], + ], + }); }); it('records an auth event naming the session it ended', async () => { - (Session.findAll as any).mockResolvedValue([buildActiveSession('s-oldest')]); + (Session.findAll as any).mockResolvedValue([{ id: 's-oldest' }]); await enforceConcurrentSessionLimit({ userId: 'user-1', limit: 1, req: req(), now: NOW }); @@ -115,12 +126,55 @@ describe('when the user is at the limit', () => { }); }); +describe('when a refresh rotates the oldest while it is evicted', () => { + it('follows the chain to the replacement and evicts that', async () => { + (Session.findAll as any).mockResolvedValue([{ id: 's-old' }]); + (Session.update as any).mockResolvedValueOnce([0]).mockResolvedValueOnce([1]); + (Session.findByPk as any).mockImplementation(async (id: string) => + id === 's-old' + ? { id: 's-old', revokedAt: null, replacedBySessionId: 's-new' } + : { id: 's-new', revokedAt: null, replacedBySessionId: null }, + ); + + const evicted = await enforceConcurrentSessionLimit({ + userId: 'user-1', + limit: 1, + req: req(), + now: NOW, + }); + + expect(evicted).toBe(1); + expect(evictedIds()).toEqual(['s-old', 's-new']); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ metadata: expect.objectContaining({ sessionId: 's-new' }) }), + ); + }); + + it.each([ + ['revoked meanwhile', { id: 's-old', revokedAt: NOW, replacedBySessionId: 's-new' }], + ['gone', null], + ])('counts nothing when the chain was %s', async (_label, row) => { + (Session.findAll as any).mockResolvedValue([{ id: 's-old' }]); + (Session.update as any).mockResolvedValue([0]); + (Session.findByPk as any).mockResolvedValue(row); + + const evicted = await enforceConcurrentSessionLimit({ + userId: 'user-1', + limit: 1, + req: req(), + now: NOW, + }); + + expect(evicted).toBe(0); + expect(AuthEventService.log).not.toHaveBeenCalled(); + }); +}); + describe('when the user is over the limit', () => { // Lowering the limit leaves users above it. They should converge on the next // sign-in rather than shedding one session per login forever. it('evicts everything above the limit in one pass', async () => { - const sessions = ['s-1', 's-2', 's-3', 's-4'].map(buildActiveSession); - (Session.findAll as any).mockResolvedValue(sessions); + (Session.findAll as any).mockResolvedValue(['s-1', 's-2', 's-3', 's-4'].map((id) => ({ id }))); const evicted = await enforceConcurrentSessionLimit({ userId: 'user-1', @@ -130,10 +184,7 @@ describe('when the user is over the limit', () => { }); expect(evicted).toBe(3); - for (const session of sessions.slice(0, 3)) { - expect(session.update).toHaveBeenCalled(); - } - expect(sessions[3].update).not.toHaveBeenCalled(); + expect(evictedIds()).toEqual(['s-1', 's-2', 's-3']); expect(AuthEventService.log).toHaveBeenCalledTimes(3); }); }); @@ -149,3 +200,85 @@ describe('when eviction fails', () => { ).resolves.toBe(0); }); }); + +describe('withConcurrentSessionSlot', () => { + const outer = { id: 'outer' }; + const savepoint = { id: 'savepoint' }; + let sequelize: { transaction: ReturnType; query: ReturnType }; + + beforeEach(() => { + sequelize = { + transaction: vi.fn(async (...args: any[]) => { + const fn = args[args.length - 1]; + return fn(args.length === 2 ? savepoint : outer); + }), + query: vi.fn(async () => []), + }; + (Session as any).sequelize = sequelize; + }); + + afterEach(() => { + delete (Session as any).sequelize; + }); + + it('creates without a transaction or lock when no limit is set', async () => { + const create = vi.fn(async () => 'created'); + + await expect( + withConcurrentSessionSlot({ userId: 'user-1', limit: null, req: req() }, create), + ).resolves.toBe('created'); + + expect(create).toHaveBeenCalledWith(); + expect(sequelize.transaction).not.toHaveBeenCalled(); + }); + + it('locks the user, evicts in a savepoint and creates in the same transaction', async () => { + (Session.findAll as any).mockResolvedValue([{ id: 's-oldest' }]); + const create = vi.fn(async () => 'created'); + + const created = await withConcurrentSessionSlot( + { userId: 'user-1', limit: 1, req: req(), now: NOW }, + create, + ); + + expect(created).toBe('created'); + expect(sequelize.query).toHaveBeenCalledWith( + 'SELECT pg_advisory_xact_lock(:lockClass, hashtext(:userId))', + expect.objectContaining({ + replacements: expect.objectContaining({ userId: 'user-1' }), + transaction: outer, + }), + ); + expect(sequelize.transaction).toHaveBeenCalledWith( + { transaction: outer }, + expect.any(Function), + ); + expect(Session.findAll).toHaveBeenCalledWith( + expect.objectContaining({ transaction: savepoint }), + ); + expect(Session.update).toHaveBeenCalledWith(expect.anything(), { + where: { id: 's-oldest', revokedAt: null, replacedBySessionId: null }, + transaction: savepoint, + }); + expect(create).toHaveBeenCalledWith(outer); + + // The cascade and the audit event read the eviction as committed, so they follow it. + const createOrder = create.mock.invocationCallOrder[0]; + expect((AuthEventService.log as any).mock.invocationCallOrder[0]).toBeGreaterThan(createOrder); + expect((revokeOrphanedChildSessions as any).mock.invocationCallOrder[0]).toBeGreaterThan( + createOrder, + ); + }); + + it('still creates the session when the eviction fails', async () => { + (Session.findAll as any).mockRejectedValue(new Error('database is down')); + const create = vi.fn(async () => 'created'); + + await expect( + withConcurrentSessionSlot({ userId: 'user-1', limit: 1, req: req() }, create), + ).resolves.toBe('created'); + + expect(create).toHaveBeenCalledWith(outer); + expect(AuthEventService.log).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/services/sessionIssueService.spec.ts b/tests/unit/services/sessionIssueService.spec.ts index ff5334b3..301ad4f5 100644 --- a/tests/unit/services/sessionIssueService.spec.ts +++ b/tests/unit/services/sessionIssueService.spec.ts @@ -33,7 +33,7 @@ vi.mock('../../../src/services/organizationService.js', () => ({ })); vi.mock('../../../src/services/concurrentSessionPolicy.js', () => ({ - enforceConcurrentSessionLimit: vi.fn(), + withConcurrentSessionSlot: vi.fn((_params: unknown, create: () => unknown) => create()), })); vi.mock('../../../src/services/loginHookService.js', async (importOriginal) => { @@ -55,7 +55,7 @@ import { signAccessToken, } from '../../../src/lib/token.js'; import { Session } from '../../../src/models/sessions.js'; -import { enforceConcurrentSessionLimit } from '../../../src/services/concurrentSessionPolicy.js'; +import { withConcurrentSessionSlot } from '../../../src/services/concurrentSessionPolicy.js'; import { runLoginHook } from '../../../src/services/loginHookService.js'; import { revokeSessionChain } from '../../../src/services/sessionService.js'; import { getDefaultOrganizationIdForUser } from '../../../src/services/organizationService.js'; @@ -512,15 +512,28 @@ describe('concurrent session limit', () => { await issueSessionAndRespond({ user: mockUser, req: mockReq(), res: mockRes() }); - expect(enforceConcurrentSessionLimit).toHaveBeenCalledWith( + expect(withConcurrentSessionSlot).toHaveBeenCalledWith( expect.objectContaining({ userId: mockUser.id, limit: 3 }), + expect.any(Function), ); - // Ordering is the point: the limit counts the session about to exist, so it - // has to run before the row is created. - const evictionOrder = (enforceConcurrentSessionLimit as any).mock.invocationCallOrder[0]; + // The slot is what creates the row, so the limit counts the session about to exist. + const slotOrder = (withConcurrentSessionSlot as any).mock.invocationCallOrder[0]; const createOrder = (Session.create as any).mock.invocationCallOrder[0]; - expect(evictionOrder).toBeLessThan(createOrder); + expect(slotOrder).toBeLessThan(createOrder); + }); + + it('creates the session inside the transaction the slot holds', async () => { + const transaction = { id: 'tx' }; + (withConcurrentSessionSlot as any).mockImplementationOnce( + (_params: unknown, create: (tx: unknown) => unknown) => create(transaction), + ); + + await issueSessionAndRespond({ user: mockUser, req: mockReq(), res: mockRes() }); + + expect(Session.create).toHaveBeenCalledWith(expect.objectContaining({ userId: mockUser.id }), { + transaction, + }); }); it('adds extraFields to the response', async () => { @@ -561,8 +574,9 @@ describe('concurrent session limit', () => { it('passes no limit through when the deployment has not set one', async () => { await issueSessionAndRespond({ user: mockUser, req: mockReq(), res: mockRes() }); - expect(enforceConcurrentSessionLimit).toHaveBeenCalledWith( + expect(withConcurrentSessionSlot).toHaveBeenCalledWith( expect.objectContaining({ limit: null }), + expect.any(Function), ); }); }); @@ -615,7 +629,7 @@ describe('login hooks', () => { message: 'Your account is on hold.', }); expect(runLoginHook).toHaveBeenCalledTimes(1); - expect(enforceConcurrentSessionLimit).not.toHaveBeenCalled(); + expect(withConcurrentSessionSlot).not.toHaveBeenCalled(); expect(Session.create).not.toHaveBeenCalled(); expect(signAccessToken).not.toHaveBeenCalled(); }); From 1f147dec6fdf26ee8b3c5475a802ae97245fd483 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Fri, 4 Dec 2026 22:36:46 -0500 Subject: [PATCH 2/2] fix(sessions): count a sign-in mid-refresh once against the limit A refresh inserts its replacement before claiming the row it replaces, so for a moment one sign-in has two heads. Counting both evicted an unrelated session. Heads are now grouped by the chain's start. --- .changeset/concurrent-session-cap.md | 2 +- src/services/concurrentSessionPolicy.ts | 20 +++-- tests/postgres/concurrentSessionLimit.spec.ts | 17 ++++ .../services/concurrentSessionPolicy.spec.ts | 77 ++++++++++++++++--- 4 files changed, 101 insertions(+), 15 deletions(-) diff --git a/.changeset/concurrent-session-cap.md b/.changeset/concurrent-session-cap.md index 43ad2950..c77a73b9 100644 --- a/.changeset/concurrent-session-cap.md +++ b/.changeset/concurrent-session-cap.md @@ -2,4 +2,4 @@ 'seamless-auth-api': patch --- -The concurrent session limit (`max_concurrent_sessions`) now evicts the sign-in that started first, rather than the session row created first. A refresh writes a new row, so a session that refreshed often used to look newest and was never the one evicted. Eviction is now conditional on the row still being the head of its chain, and follows a refresh that rotated it so the replacement is evicted instead. Counting, evicting and creating a session now hold a per-user lock, so parallel sign-ins can no longer each count the same sessions and leave the user above the limit. With no limit configured, nothing is locked. +The concurrent session limit (`max_concurrent_sessions`) now evicts the sign-in that started first, rather than the session row created first. A refresh writes a new row, so a session that refreshed often used to look newest and was never the one evicted. Eviction is now conditional on the row still being the head of its chain, and follows a refresh that rotated it so the replacement is evicted instead. Counting, evicting and creating a session now hold a per-user lock, so parallel sign-ins can no longer each count the same sessions and leave the user above the limit. A refresh that has inserted its replacement but not yet claimed it counts as one sign-in. With no limit configured, nothing is locked. diff --git a/src/services/concurrentSessionPolicy.ts b/src/services/concurrentSessionPolicy.ts index a6d4bcb1..f7c81ff8 100644 --- a/src/services/concurrentSessionPolicy.ts +++ b/src/services/concurrentSessionPolicy.ts @@ -99,17 +99,27 @@ async function evictSurplus( ...inTransaction(transaction), }); + // A refresh inserts its replacement before it claims the row it replaces, so for a moment + // one sign-in has two heads. Both carry the chain's start, so heads are counted by it. + const signIns = new Map(); + for (const session of active) { + const startedAt = new Date(session.chainStartedAt ?? session.createdAt).getTime(); + signIns.set(startedAt, [...(signIns.get(startedAt) ?? []), session]); + } + // The incoming session is not stored yet, so the limit is compared against // what is already there plus the one about to be added. - const surplus = active.length + 1 - limit; + const surplus = signIns.size + 1 - limit; const evicted: Session[] = []; - for (const session of active.slice(0, Math.max(surplus, 0))) { - const revoked = await evictChain(session, now, transaction); - if (revoked) evicted.push(revoked); + for (const heads of [...signIns.values()].slice(0, Math.max(surplus, 0))) { + for (const head of heads) { + const revoked = await evictChain(head, now, transaction); + if (revoked) evicted.push(revoked); + } } - return { evicted, activeBefore: active.length }; + return { evicted, activeBefore: signIns.size }; } // After the evictions are committed, so the cascade reads them as ended. diff --git a/tests/postgres/concurrentSessionLimit.spec.ts b/tests/postgres/concurrentSessionLimit.spec.ts index 9f87ce41..cfcee92a 100644 --- a/tests/postgres/concurrentSessionLimit.spec.ts +++ b/tests/postgres/concurrentSessionLimit.spec.ts @@ -99,3 +99,20 @@ describe('the concurrent session limit', () => { expect(heads[0].id).not.toBe(replacement.id); }); }); + +describe('a refresh caught between inserting and claiming', () => { + it('counts as one sign-in, so no other session is evicted for it', async () => { + const userId = await createUser(); + const other = await Session.create(sessionAttributes(userId, new Date(Date.now() - 120_000))); + const started = new Date(Date.now() - 60_000); + await Session.create(sessionAttributes(userId, started)); + // The replacement a refresh has inserted and not yet linked. + await Session.create(sessionAttributes(userId, started)); + + const evicted = await enforceConcurrentSessionLimit({ userId, limit: 3, req }); + + expect(evicted).toBe(0); + await other.reload(); + expect(other.revokedAt).toBeNull(); + }); +}); diff --git a/tests/unit/services/concurrentSessionPolicy.spec.ts b/tests/unit/services/concurrentSessionPolicy.spec.ts index 2992e82b..2f7e68b9 100644 --- a/tests/unit/services/concurrentSessionPolicy.spec.ts +++ b/tests/unit/services/concurrentSessionPolicy.spec.ts @@ -12,6 +12,12 @@ import { revokeOrphanedChildSessions } from '../../../src/services/sessionServic const NOW = new Date('2026-08-30T12:00:00.000Z'); +let started = 0; + +function head(id: string, chainStartedAt = new Date(NOW.getTime() - 60_000 + started++)) { + return { id, chainStartedAt, createdAt: chainStartedAt }; +} + function req() { return { ip: '127.0.0.1', headers: {}, get: () => undefined } as never; } @@ -54,7 +60,7 @@ describe('when no limit is configured', () => { describe('when the user is below the limit', () => { it('leaves existing sessions alone', async () => { - (Session.findAll as any).mockResolvedValue([{ id: 's-1' }]); + (Session.findAll as any).mockResolvedValue([head('s-1')]); const evicted = await enforceConcurrentSessionLimit({ userId: 'user-1', @@ -71,7 +77,7 @@ describe('when the user is below the limit', () => { describe('when the user is at the limit', () => { it('revokes the oldest head, conditionally, to make room for the new session', async () => { - (Session.findAll as any).mockResolvedValue([{ id: 's-oldest' }, { id: 's-newer' }]); + (Session.findAll as any).mockResolvedValue([head('s-oldest'), head('s-newer')]); const evicted = await enforceConcurrentSessionLimit({ userId: 'user-1', @@ -86,13 +92,15 @@ describe('when the user is at the limit', () => { { revokedAt: NOW, revokedReason: EVICTION_REASON }, { where: { id: 's-oldest', revokedAt: null, replacedBySessionId: null } }, ); - expect(revokeOrphanedChildSessions).toHaveBeenCalledWith({ id: 's-oldest' }); + expect(revokeOrphanedChildSessions).toHaveBeenCalledWith( + expect.objectContaining({ id: 's-oldest' }), + ); }); // A refresh writes a new row, so ordering by the row let a session that refreshes // often stay newest forever. it('asks for active sessions by when their sign-in started', async () => { - (Session.findAll as any).mockResolvedValue([{ id: 's-1' }]); + (Session.findAll as any).mockResolvedValue([head('s-1')]); await enforceConcurrentSessionLimit({ userId: 'user-1', limit: 1, req: req(), now: NOW }); @@ -112,7 +120,7 @@ describe('when the user is at the limit', () => { }); it('records an auth event naming the session it ended', async () => { - (Session.findAll as any).mockResolvedValue([{ id: 's-oldest' }]); + (Session.findAll as any).mockResolvedValue([head('s-oldest')]); await enforceConcurrentSessionLimit({ userId: 'user-1', limit: 1, req: req(), now: NOW }); @@ -128,7 +136,7 @@ describe('when the user is at the limit', () => { describe('when a refresh rotates the oldest while it is evicted', () => { it('follows the chain to the replacement and evicts that', async () => { - (Session.findAll as any).mockResolvedValue([{ id: 's-old' }]); + (Session.findAll as any).mockResolvedValue([head('s-old')]); (Session.update as any).mockResolvedValueOnce([0]).mockResolvedValueOnce([1]); (Session.findByPk as any).mockImplementation(async (id: string) => id === 's-old' @@ -154,7 +162,7 @@ describe('when a refresh rotates the oldest while it is evicted', () => { ['revoked meanwhile', { id: 's-old', revokedAt: NOW, replacedBySessionId: 's-new' }], ['gone', null], ])('counts nothing when the chain was %s', async (_label, row) => { - (Session.findAll as any).mockResolvedValue([{ id: 's-old' }]); + (Session.findAll as any).mockResolvedValue([head('s-old')]); (Session.update as any).mockResolvedValue([0]); (Session.findByPk as any).mockResolvedValue(row); @@ -170,11 +178,62 @@ describe('when a refresh rotates the oldest while it is evicted', () => { }); }); +describe('when a refresh has inserted a replacement it has not claimed yet', () => { + // Both heads carry the chain's start. Counted as two, they cost an unrelated session its slot. + it('counts the sign-in once and evicts both of its heads when it is the oldest', async () => { + const chainStart = new Date(NOW.getTime() - 120_000); + (Session.findAll as any).mockResolvedValue([ + head('s-a', chainStart), + head('s-a-next', chainStart), + head('s-b'), + ]); + + const evicted = await enforceConcurrentSessionLimit({ + userId: 'user-1', + limit: 2, + req: req(), + now: NOW, + }); + + expect(evicted).toBe(2); + expect(evictedIds()).toEqual(['s-a', 's-a-next']); + }); + + it('falls back to the row creation time for a chain with no recorded start', async () => { + (Session.findAll as any).mockResolvedValue([ + { id: 's-legacy', chainStartedAt: null, createdAt: new Date(NOW.getTime() - 300_000) }, + head('s-b'), + ]); + + await enforceConcurrentSessionLimit({ userId: 'user-1', limit: 2, req: req(), now: NOW }); + + expect(evictedIds()).toEqual(['s-legacy']); + }); + + it('leaves the user alone when the sign-ins fit', async () => { + const chainStart = new Date(NOW.getTime() - 120_000); + (Session.findAll as any).mockResolvedValue([ + head('s-b', new Date(NOW.getTime() - 180_000)), + head('s-a', chainStart), + head('s-a-next', chainStart), + ]); + + const evicted = await enforceConcurrentSessionLimit({ + userId: 'user-1', + limit: 3, + req: req(), + now: NOW, + }); + + expect(evicted).toBe(0); + }); +}); + describe('when the user is over the limit', () => { // Lowering the limit leaves users above it. They should converge on the next // sign-in rather than shedding one session per login forever. it('evicts everything above the limit in one pass', async () => { - (Session.findAll as any).mockResolvedValue(['s-1', 's-2', 's-3', 's-4'].map((id) => ({ id }))); + (Session.findAll as any).mockResolvedValue(['s-1', 's-2', 's-3', 's-4'].map((id) => head(id))); const evicted = await enforceConcurrentSessionLimit({ userId: 'user-1', @@ -233,7 +292,7 @@ describe('withConcurrentSessionSlot', () => { }); it('locks the user, evicts in a savepoint and creates in the same transaction', async () => { - (Session.findAll as any).mockResolvedValue([{ id: 's-oldest' }]); + (Session.findAll as any).mockResolvedValue([head('s-oldest')]); const create = vi.fn(async () => 'created'); const created = await withConcurrentSessionSlot(