Skip to content
Merged
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/enroll-after-first-factor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'seamless-auth-api': patch
---

A user who adds their first passkey or authenticator app can add recovery codes, a phone or another factor in the same sign-in again. Since 0.24.0 the new factor made those routes ask for a step-up that only a factor from before the sign-in can pass, so a new user was stopped between their first passkey and their recovery codes until they signed in again. Only a factor enrolled before the session signed in now makes enrollment ask for a step-up. A factor added during the session is treated like no factor, which needs a sign-in from the last five minutes.
19 changes: 15 additions & 4 deletions src/middleware/requireFactorEnrollmentProof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
*/

import { NextFunction, Request, Response } from 'express';
import { Op } from 'sequelize';

import { Credential } from '../models/credentials.js';
import { TotpCredential } from '../models/totpCredentials.js';
import {
findCurrentSession,
findSessionSignInTime,
FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS,
getStepUpStatusFromSession,
serializeStepUpStatus,
Expand All @@ -20,10 +22,19 @@ import {
refuseDeviceSessionWithoutStepUp,
} from './requireDeviceSessionStepUp.js';

async function hasStepUpFactor(userId: string) {
/**
* Only a factor from before the session's sign-in can satisfy a step-up, so only one of those
* makes the account prove itself with a step-up. Counting one added during this session would
* demand a step-up nothing can pass, stranding a new user between their first passkey and
* their recovery codes. When the sign-in time cannot be read, every factor counts.
*/
async function hasStepUpFactor(userId: string, signedInAt: Date | null) {
const before = signedInAt ? { [Op.lt]: signedInAt } : undefined;
const [passkeys, totp] = await Promise.all([
Credential.count({ where: { userId } }),
TotpCredential.count({ where: { userId, enabled: true } }),
Credential.count({ where: before ? { userId, createdAt: before } : { userId } }),
TotpCredential.count({
where: before ? { userId, enabled: true, verifiedAt: before } : { userId, enabled: true },
}),
]);

return passkeys > 0 || totp > 0;
Expand Down Expand Up @@ -61,7 +72,7 @@ export const requireFactorEnrollmentProof: DeviceStepUpAwareHandler = async (
return;
}

if (await hasStepUpFactor(userId)) {
if (await hasStepUpFactor(userId, await findSessionSignInTime(session))) {
const status = getStepUpStatusFromSession(session);

if (!status.fresh) {
Expand Down
150 changes: 150 additions & 0 deletions tests/postgres/factorEnrollmentAfterSignIn.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { randomUUID } from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';

import { invalidateSystemConfigCache } from '../../src/config/getSystemConfig.js';
import { Credential } from '../../src/models/credentials.js';
import { getSequelize, initializeModels } from '../../src/models/index.js';
import { Session } from '../../src/models/sessions.js';
import { TotpCredential } from '../../src/models/totpCredentials.js';
import { User } from '../../src/models/users.js';
import { buildSystemConfig } from '../factories/systemConfigFactory.js';

type App = Awaited<ReturnType<typeof import('../../src/app.js').createApp>>;
type Tokens = typeof import('../../src/lib/token.js');

let app: App;
let tokens: Tokens;
const savedEnv: Record<string, string | undefined> = {};

const MINUTE_MS = 60_000;

beforeAll(async () => {
for (const [key, value] of Object.entries({
ISSUER: 'http://localhost:5312',
DISABLE_AUTH_RATE_LIMITS: 'true',
SEAMLESS_DEV_KEYS_DIR: fs.mkdtempSync(path.join(os.tmpdir(), 'seamless-keys-')),
})) {
savedEnv[key] = process.env[key];
process.env[key] = value;
}

await initializeModels();

for (const [key, value] of Object.entries(buildSystemConfig())) {
await getSequelize().query(
`INSERT INTO system_config (key, value, "createdAt", "updatedAt")
VALUES (:key, CAST(:value AS jsonb), now(), now())
ON CONFLICT (key) DO NOTHING`,
{ replacements: { key, value: JSON.stringify(value) } },
);
}
invalidateSystemConfigCache();

tokens = await import('../../src/lib/token.js');
const { initDevSigningKey } = await import('../../src/utils/signingKeyStore.js');
const { createApp } = await import('../../src/app.js');
initDevSigningKey();
app = await createApp();
});

afterAll(async () => {
await getSequelize().query(`DELETE FROM users WHERE email LIKE :pattern`, {
replacements: { pattern: '%@enroll-after-sign-in.test' },
});
invalidateSystemConfigCache();
for (const [key, value] of Object.entries(savedEnv)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
await getSequelize().close();
});

beforeEach(() => {
invalidateSystemConfigCache();
});

/** A new account that signed in a minute ago, as a first sign-up does. */
async function signedInMinuteAgo() {
const user = await User.create({
email: `${randomUUID()}@enroll-after-sign-in.test`,
phone: null,
roles: ['user'],
} as never);
const signedInAt = new Date(Date.now() - MINUTE_MS);
const session = await Session.create({
userId: user.id,
mode: 'server',
refreshTokenLookup: randomUUID().replaceAll('-', ''),
expiresAt: new Date(Date.now() + 3_600_000),
idleExpiresAt: new Date(Date.now() + 3_600_000),
lastUsedAt: new Date(),
chainStartedAt: signedInAt,
authTime: signedInAt,
});
const token = await tokens.signAccessToken(session.id, user.id, ['user'], null);

return { user, token };
}

function addPasskey(userId: string) {
return Credential.create({
id: randomUUID(),
userId,
publicKey: Buffer.from('key'),
counter: 0,
} as never);
}

async function backdatePasskeys(userId: string) {
await getSequelize().query('UPDATE credentials SET "createdAt" = :at WHERE "userId" = :userId', {
replacements: { at: new Date(Date.now() - 24 * 60 * MINUTE_MS), userId },
});
}

function generateRecoveryCodes(token: string) {
return request(app).post('/recovery-codes').set('Authorization', `Bearer ${token}`);
}

describe('adding a factor after the first one in the same sign-in', () => {
it('lets a new user generate recovery codes right after their first passkey', async () => {
const { user, token } = await signedInMinuteAgo();
await addPasskey(user.id);

const res = await generateRecoveryCodes(token);

expect(res.status, JSON.stringify(res.body)).toBe(201);
});

it('does the same right after their first authenticator app', async () => {
const { user, token } = await signedInMinuteAgo();
await TotpCredential.create({
userId: user.id,
secretCiphertext: 'c',
secretIv: 'i',
secretTag: 't',
issuer: 'Seamless',
accountName: user.email,
enabled: true,
verifiedAt: new Date(),
} as never);

const res = await generateRecoveryCodes(token);

expect(res.status, JSON.stringify(res.body)).toBe(201);
});

it('still needs a step-up once a factor predates the sign-in', async () => {
const { user, token } = await signedInMinuteAgo();
await addPasskey(user.id);
await backdatePasskeys(user.id);

const res = await generateRecoveryCodes(token);

expect(res.status).toBe(403);
expect(res.body.error).toBe('step_up_required');
});
});
37 changes: 36 additions & 1 deletion tests/unit/middleware/requireFactorEnrollmentProof.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Op } from 'sequelize';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { requireFactorEnrollmentProof } from '../../../src/middleware/requireFactorEnrollmentProof';
Expand Down Expand Up @@ -90,7 +91,7 @@ describe('requireFactorEnrollmentProof', () => {
await requireFactorEnrollmentProof(buildReq(), res, next);

expect(TotpCredential.count).toHaveBeenCalledWith({
where: { userId: 'user-1', enabled: true },
where: { userId: 'user-1', enabled: true, verifiedAt: { [Op.lt]: expect.any(Date) } },
});
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ error: 'step_up_required' }));
});
Expand All @@ -105,6 +106,40 @@ describe('requireFactorEnrollmentProof', () => {
});
});

describe('an account whose factors were all added during this sign-in', () => {
it('counts only factors from before the sign-in', async () => {
const signedInAt = new Date(Date.now() - 2 * MINUTE_MS);
withSession({ chainStartedAt: signedInAt, createdAt: signedInAt, authTime: signedInAt });

await requireFactorEnrollmentProof(buildReq(), res, next);

expect(Credential.count).toHaveBeenCalledWith({
where: { userId: 'user-1', createdAt: { [Op.lt]: signedInAt } },
});
expect(TotpCredential.count).toHaveBeenCalledWith({
where: { userId: 'user-1', enabled: true, verifiedAt: { [Op.lt]: signedInAt } },
});
});

it('passes a recent sign-in, as an account with no factor does', async () => {
withSession({ authTime: new Date(Date.now() - 2 * MINUTE_MS) });

await requireFactorEnrollmentProof(buildReq(), res, next);

expect(next).toHaveBeenCalled();
});

it('counts every factor when the sign-in time cannot be read', async () => {
(Credential.count as any).mockResolvedValue(1);
withSession({ chainStartedAt: null, createdAt: null, stepUpVerifiedAt: null });

await requireFactorEnrollmentProof(buildReq(), res, next);

expect(Credential.count).toHaveBeenCalledWith({ where: { userId: 'user-1' } });
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ error: 'step_up_required' }));
});
});

describe('an account with no factor', () => {
it('passes a recent sign-in', async () => {
withSession({ authTime: new Date(Date.now() - 4 * MINUTE_MS) });
Expand Down