Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/concurrent-session-cap.md
Original file line number Diff line number Diff line change
@@ -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. A refresh that has inserted its replacement but not yet claimed it counts as one sign-in. With no limit configured, nothing is locked.
239 changes: 182 additions & 57 deletions src/services/concurrentSessionPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -17,13 +17,141 @@ 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.
*
* 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.
*
* 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.
* 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<Evictions> {
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),
});

// 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<number, Session[]>();
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 = signIns.size + 1 - limit;
const evicted: Session[] = [];

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: signIns.size };
}

// 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,
Expand All @@ -33,72 +161,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<number> {
const { userId, limit, req } = params;
export async function enforceConcurrentSessionLimit(params: LimitParams): Promise<number> {
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<T>(
params: LimitParams,
create: (transaction?: Transaction) => Promise<T>,
): Promise<T> {
const { userId, limit } = params;

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,
},
});
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,
});

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;
}
22 changes: 11 additions & 11 deletions src/services/sessionIssuance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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 },
Expand Down
Loading
Loading