diff --git a/.changeset/credential-delete-ends-sessions.md b/.changeset/credential-delete-ends-sessions.md new file mode 100644 index 00000000..f43bfb03 --- /dev/null +++ b/.changeset/credential-delete-ends-sessions.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +Removing a passkey with `DELETE /users/credentials` now signs out every other session on the account. The session that made the request is kept, since it has just passed a step-up. A passkey is usually removed because its device is lost or no longer trusted, and a session signed in from that device used to stay valid until it expired. The `credentials_deleted` audit event records how many sessions were ended, and each one is revoked with the reason `credential_deleted`. Access tokens a server adapter verifies locally still last until they expire. diff --git a/openapi.json b/openapi.json index 4955a6a7..fcfacfa9 100644 --- a/openapi.json +++ b/openapi.json @@ -36254,7 +36254,7 @@ }, "delete": { "summary": "Delete credential", - "description": "Needs a fresh step-up.", + "description": "Needs a fresh step-up. Signs out every other session on the account, keeping the one that made the request, since a removed passkey is often a lost device.", "tags": ["Users"], "security": [{ "bearerAuth": [] }], "requestBody": { diff --git a/src/controllers/user.ts b/src/controllers/user.ts index cda2290a..816340ec 100644 --- a/src/controllers/user.ts +++ b/src/controllers/user.ts @@ -13,11 +13,15 @@ import { refuseLastAdminChange, wouldLeaveNoAdmin } from '../services/adminConti import { serializeCredential } from '../services/apiResponseSerializers.js'; import { AuthEventService } from '../services/authEventService.js'; import { listOrganizationsForUser } from '../services/organizationService.js'; +import { revokeOtherSessions } from '../services/sessionRevocation.js'; +import { revokeOrphanedChildSessions } from '../services/sessionService.js'; import { AuthenticatedRequest } from '../types/types.js'; import getLogger from '../utils/logger.js'; const logger = getLogger('user'); +export const CREDENTIAL_DELETED_REASON = 'credential_deleted'; + export const getUser = async (req: Request, res: Response) => { logger.debug('Retrieving user'); const authReq = req as AuthenticatedRequest; @@ -215,13 +219,23 @@ export const deleteCredential = async (req: Request, res: Response) => { }); } + // A passkey is removed most often because its device is gone, and a session signed in + // from that device would otherwise outlive it. The caller's own session just stepped up. + // Revoked before the delete, so a failure leaves the passkey for a retry to remove. + const revokedSessions = await revokeOtherSessions( + authUser.id, + authReq.sessionId, + CREDENTIAL_DELETED_REASON, + ); + await revokeOrphanedChildSessions({ userId: authUser.id, parentSessionId: null }); + await cred.destroy(); await AuthEventService.log({ userId: authUser.id, type: 'credentials_deleted', req, - metadata: { credential: 'passkey', credentialId: cred.id }, + metadata: { credential: 'passkey', credentialId: cred.id, revokedSessions }, }); return res.json({ message: 'Credential deleted' }); diff --git a/src/generated/api.ts b/src/generated/api.ts index 1d54d40c..4a8f4fdb 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -34704,7 +34704,7 @@ export interface paths { }; /** * Delete credential - * @description Needs a fresh step-up. + * @description Needs a fresh step-up. Signs out every other session on the account, keeping the one that made the request, since a removed passkey is often a lost device. */ delete: { parameters: { diff --git a/src/routes/users.routes.ts b/src/routes/users.routes.ts index 0f910b3f..af65baa0 100644 --- a/src/routes/users.routes.ts +++ b/src/routes/users.routes.ts @@ -99,7 +99,9 @@ usersRouter.delete( auth: 'access', tags: ['Users'], summary: 'Delete credential', - description: 'Needs a fresh step-up.', + description: + 'Needs a fresh step-up. Signs out every other session on the account, keeping the one ' + + 'that made the request, since a removed passkey is often a lost device.', schemas: { body: DeleteCredentialRequestSchema, diff --git a/src/services/sessionRevocation.ts b/src/services/sessionRevocation.ts index 262483ea..66256769 100644 --- a/src/services/sessionRevocation.ts +++ b/src/services/sessionRevocation.ts @@ -4,7 +4,7 @@ * See LICENSE file in the project root for full license information */ -import type { Transaction } from 'sequelize'; +import { Op, type Transaction } from 'sequelize'; import { Session } from '../models/sessions.js'; import { User } from '../models/users.js'; @@ -12,6 +12,10 @@ import { User } from '../models/users.js'; /** What a session exchanged from another records when that parent ends (ADR 0003, X4). */ export const PARENT_SESSION_ENDED = 'parent_session_ended'; +const MIN_REVOKE_PASSES = 2; +const MAX_REVOKE_PASSES = 5; +const MAX_CHAIN_STEPS = 10_000; + /** * Ends every session the given users hold, including one a refresh is creating right now. * @@ -43,6 +47,64 @@ export async function revokeAllSessionsForUsers( return revoked; } +// Follows the caller's session to the head of the sign-in it belongs to: through the parent +// an exchanged session was minted from, then forward through rotations, so a refresh of the +// caller's own chain mid-revoke does not sign the caller out. +async function currentHeadOf(sessionId: string): Promise { + let current = await Session.findByPk(sessionId); + let steps = 0; + + while (current?.parentSessionId && steps < MAX_CHAIN_STEPS) { + current = await Session.findByPk(current.parentSessionId); + steps += 1; + } + + while (current?.replacedBySessionId && steps < MAX_CHAIN_STEPS) { + current = await Session.findByPk(current.replacedBySessionId); + steps += 1; + } + + return current?.id ?? sessionId; +} + +/** + * Ends every sign-in the user holds except the one `keepSessionId` belongs to. + * + * Only chain heads are revoked, and exchanged sessions are left to end with their parent. A + * rotation inserts its replacement before claiming the row it replaces, so a replacement one + * pass's snapshot missed is visible to the next. At least two passes run, and more while a + * pass still finds something, bounded so a client refreshing in a loop cannot hold this + * open. + */ +export async function revokeOtherSessions( + userId: string, + keepSessionId: string, + reason: string, +): Promise { + let total = 0; + + for (let pass = 0; pass < MAX_REVOKE_PASSES; pass++) { + const keep = await currentHeadOf(keepSessionId); + const [revoked] = await Session.update( + { revokedAt: new Date(), revokedReason: reason }, + { + where: { + userId, + id: { [Op.ne]: keep }, + revokedAt: null, + replacedBySessionId: null, + parentSessionId: null, + }, + }, + ); + + total += revoked; + if (revoked === 0 && pass >= MIN_REVOKE_PASSES - 1) break; + } + + return total; +} + /** * Whether a revoke-all for the session's owner happened at or after the session began. * A session with no creation time is treated as revoked, so a malformed row fails closed. diff --git a/tests/integration/user/user.spec.ts b/tests/integration/user/user.spec.ts index ecf5facd..fbbef517 100644 --- a/tests/integration/user/user.spec.ts +++ b/tests/integration/user/user.spec.ts @@ -1,3 +1,4 @@ +import { Op } from 'sequelize'; import request from 'supertest'; import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { Application } from 'express'; @@ -9,6 +10,7 @@ import { User } from '../../../src/models/users.js'; import { AuthEventService } from '../../../src/services/authEventService.js'; import { buildCredential } from '../../factories/credentialFactory.js'; import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; +import { revokeOrphanedChildSessions } from '../../../src/services/sessionService.js'; let app: Application; @@ -198,6 +200,52 @@ describe('DELETE /users/credentials', () => { ); }); + it('signs out every other session and keeps the caller', async () => { + const cred = buildCredential(); + + (Credential.findOne as any).mockResolvedValue(cred); + (Credential.count as any).mockResolvedValue(2); + (Session.update as any).mockResolvedValueOnce([2]).mockResolvedValue([0]); + + const res = await request(app).delete('/users/credentials').send({ id: 'cred-1' }); + + expect(res.status).toBe(200); + expect(Session.update).toHaveBeenCalledWith( + { revokedAt: expect.any(Date), revokedReason: 'credential_deleted' }, + { + where: expect.objectContaining({ + userId: 'user-1', + id: { [Op.ne]: 'session-1' }, + revokedAt: null, + }), + }, + ); + expect(revokeOrphanedChildSessions).toHaveBeenCalledWith({ + userId: 'user-1', + parentSessionId: null, + }); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'credentials_deleted', + metadata: expect.objectContaining({ revokedSessions: 2 }), + }), + ); + }); + + it('signs nothing out when the credential is not deleted', async () => { + const cred = buildCredential(); + + (Credential.findOne as any).mockResolvedValue(cred); + (Credential.count as any).mockResolvedValue(1); + + await request(app).delete('/users/credentials').send({ id: 'cred-1' }); + + expect(Session.update).not.toHaveBeenCalledWith( + expect.objectContaining({ revokedReason: 'credential_deleted' }), + expect.anything(), + ); + }); + it('rejects deleting last credential', async () => { const cred = buildCredential(); @@ -217,6 +265,18 @@ describe('DELETE /users/credentials', () => { expect(res.status).toBe(404); }); + it('keeps the passkey when the sessions cannot be revoked', async () => { + const cred = buildCredential(); + (Credential.findOne as any).mockResolvedValue(cred); + (Credential.count as any).mockResolvedValue(2); + (Session.update as any).mockRejectedValue(new Error('boom')); + + const res = await request(app).delete('/users/credentials').send({ id: 'cred-1' }); + + expect(res.status).toBe(500); + expect(cred.destroy).not.toHaveBeenCalled(); + }); + it('returns 500 when destroy fails', async () => { const cred = buildCredential(); (cred.destroy as any).mockRejectedValue(new Error('boom')); diff --git a/tests/postgres/sessionRevocation.spec.ts b/tests/postgres/sessionRevocation.spec.ts index 14806b9a..8d3ca7a1 100644 --- a/tests/postgres/sessionRevocation.spec.ts +++ b/tests/postgres/sessionRevocation.spec.ts @@ -2,7 +2,10 @@ import { randomUUID } from 'crypto'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { getSequelize, initializeModels } from '../../src/models/index.js'; -import { revokeAllSessionsForUsers } from '../../src/services/sessionRevocation.js'; +import { + revokeAllSessionsForUsers, + revokeOtherSessions, +} from '../../src/services/sessionRevocation.js'; import { claimSessionRotation, validateSessionRecord } from '../../src/services/sessionService.js'; type Models = Awaited>; @@ -86,3 +89,61 @@ describe('revoking every session for a user', () => { expect(await validateSessionRecord(current.id)).toBeNull(); }); }); + +describe('revoking every session but the caller', () => { + it('ends the other heads and keeps the caller, its history and other users', async () => { + const userId = await createUser(); + const other = await createUser(); + const caller = await createSession(userId); + const callerNext = await createSession(userId); + await claimSessionRotation(caller, callerNext.id); + const elsewhere = await createSession(userId); + const untouched = await createSession(other); + + const revoked = await revokeOtherSessions(userId, callerNext.id, 'credential_deleted'); + + expect(revoked).toBe(1); + await elsewhere.reload(); + expect(elsewhere.revokedReason).toBe('credential_deleted'); + expect(await validateSessionRecord(callerNext.id)).not.toBeNull(); + await caller.reload(); + expect(caller.revokedAt).toBeNull(); + await untouched.reload(); + expect(untouched.revokedAt).toBeNull(); + }); + + it('leaves a rotation that races it unable to claim its session', async () => { + const userId = await createUser(); + const keep = await createSession(userId); + const current = await createSession(userId); + + const [replacement] = await Promise.all([ + createSession(userId), + revokeOtherSessions(userId, keep.id, 'credential_deleted'), + ]); + const claimed = await claimSessionRotation(current, replacement.id); + + expect(claimed).toBe(false); + expect(await validateSessionRecord(current.id)).toBeNull(); + }); +}); + +describe('revoking every session but an exchanged caller', () => { + it('keeps the rotated head of the parent sign-in and its child', async () => { + const userId = await createUser(); + const parent = await createSession(userId); + const child = await createSession(userId); + await child.update({ parentSessionId: parent.id }); + const parentNext = await createSession(userId); + await claimSessionRotation(parent, parentNext.id); + const elsewhere = await createSession(userId); + + const revoked = await revokeOtherSessions(userId, child.id, 'credential_deleted'); + + expect(revoked).toBe(1); + await elsewhere.reload(); + expect(elsewhere.revokedAt).not.toBeNull(); + expect(await validateSessionRecord(parentNext.id)).not.toBeNull(); + expect(await validateSessionRecord(child.id)).not.toBeNull(); + }); +}); diff --git a/tests/unit/services/sessionRevocation.spec.ts b/tests/unit/services/sessionRevocation.spec.ts index 81dbade3..e79f421a 100644 --- a/tests/unit/services/sessionRevocation.spec.ts +++ b/tests/unit/services/sessionRevocation.spec.ts @@ -1,3 +1,4 @@ +import { Op } from 'sequelize'; import { beforeEach, describe, expect, it } from 'vitest'; import { Session } from '../../../src/models/sessions.js'; @@ -5,6 +6,7 @@ import { User } from '../../../src/models/users.js'; import { isRevokedByCutoff, revokeAllSessionsForUsers, + revokeOtherSessions, } from '../../../src/services/sessionRevocation.js'; describe('revokeAllSessionsForUsers', () => { @@ -49,6 +51,76 @@ describe('revokeAllSessionsForUsers', () => { }); }); +describe('revokeOtherSessions', () => { + const where = (keep: string) => ({ + where: { + userId: 'user-1', + id: { [Op.ne]: keep }, + revokedAt: null, + replacedBySessionId: null, + parentSessionId: null, + }, + }); + + it('revokes the other chain heads, keeps the caller and runs a second pass', async () => { + (Session.update as any).mockResolvedValueOnce([2]).mockResolvedValueOnce([0]); + + const revoked = await revokeOtherSessions('user-1', 'session-1', 'credential_deleted'); + + expect(revoked).toBe(2); + expect(Session.update).toHaveBeenCalledTimes(2); + expect(Session.update).toHaveBeenCalledWith( + { revokedAt: expect.any(Date), revokedReason: 'credential_deleted' }, + where('session-1'), + ); + }); + + // A pass that raced a rotation can find nothing, while the replacement it missed is live. + it('runs a second pass even when the first revokes nothing', async () => { + (Session.update as any) + .mockResolvedValueOnce([0]) + .mockResolvedValueOnce([1]) + .mockResolvedValueOnce([0]); + + const revoked = await revokeOtherSessions('user-1', 'session-1', 'credential_deleted'); + + expect(revoked).toBe(1); + expect(Session.update).toHaveBeenCalledTimes(3); + }); + + it('stops after a bounded number of passes', async () => { + (Session.update as any).mockResolvedValue([1]); + + const revoked = await revokeOtherSessions('user-1', 'session-1', 'credential_deleted'); + + expect(revoked).toBe(5); + expect(Session.update).toHaveBeenCalledTimes(5); + }); + + it('keeps the current head of the sign-in an exchanged caller was minted from', async () => { + const rows: Record = { + child: { id: 'child', parentSessionId: 'parent-old', replacedBySessionId: null }, + 'parent-old': { id: 'parent-old', parentSessionId: null, replacedBySessionId: 'parent-new' }, + 'parent-new': { id: 'parent-new', parentSessionId: null, replacedBySessionId: null }, + }; + (Session.findByPk as any).mockImplementation(async (id: string) => rows[id] ?? null); + (Session.update as any).mockResolvedValue([0]); + + await revokeOtherSessions('user-1', 'child', 'credential_deleted'); + + expect(Session.update).toHaveBeenCalledWith(expect.anything(), where('parent-new')); + }); + + it('keeps the named session when it cannot be read', async () => { + (Session.findByPk as any).mockResolvedValue(null); + (Session.update as any).mockResolvedValue([0]); + + await revokeOtherSessions('user-1', 'session-1', 'credential_deleted'); + + expect(Session.update).toHaveBeenCalledWith(expect.anything(), where('session-1')); + }); +}); + describe('isRevokedByCutoff', () => { const cutoff = new Date('2026-10-22T12:00:00Z');