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/credential-delete-ends-sessions.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
16 changes: 15 additions & 1 deletion src/controllers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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' });
Expand Down
2 changes: 1 addition & 1 deletion src/generated/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
4 changes: 3 additions & 1 deletion src/routes/users.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
64 changes: 63 additions & 1 deletion src/services/sessionRevocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
* 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';

/** 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.
*
Expand Down Expand Up @@ -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<string> {
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<number> {
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.
Expand Down
60 changes: 60 additions & 0 deletions tests/integration/user/user.spec.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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;

Expand Down Expand Up @@ -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();

Expand All @@ -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'));
Expand Down
63 changes: 62 additions & 1 deletion tests/postgres/sessionRevocation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReturnType<typeof initializeModels>>;
Expand Down Expand Up @@ -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();
});
});
Loading
Loading