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
10 changes: 10 additions & 0 deletions .changeset/sign-in-flow-limits.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'seamless-auth-api': patch
---

Tightens three sign-in flows.

- `POST /webauthn/login/start` and `POST /webauthn/login/finish` are now rate limited per attempt (10 per window) and per address (ten times `flow_rate_limits.otp.perIp`, 100 by default). `GET /magic-link/check` is limited per attempt (300 per window, enough to poll every few seconds for the whole life of a link). These use the `flow_rate_limits` window. Before, only the global limiter applied. No cap spans an account's attempts: a pre-auth token comes from an address alone, so a stranger could spend that cap to block the owner.
- A passkey sign-in start that matches no credential on the account is now recorded as `webauthn_login_failed` instead of `login_failed`, so it no longer counts toward account lockout. Anyone holding a pre-auth token for an address could otherwise lock its owner out by asking for a credential id the account does not have.
- Issuing a WebAuthn challenge now deletes the user's spent and expired challenge rows. Before, every ceremony start left a row behind permanently.
- OAuth sign-in now refuses an account whose `revoked` flag is set, answering 403 `login_method_disabled`, before claiming or linking it. It was the one sign-in route that did not check the flag.
2 changes: 1 addition & 1 deletion openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -17752,7 +17752,7 @@
"/oauth/{providerId}/callback": {
"post": {
"summary": "Finish OAuth login",
"description": "Answers 403 with `code: oauth_provider_retired` when an organization the user belongs to has retired this provider, and 403 `login_method_disabled` when the account has to sign in with a passkey (phishing-resistant-only mode, or the account holds a passkey and `passkey_login_fallback_enabled` is off). A success carries `nextStep: enroll_passkey` when the provider has `promptPasskeyEnrollment` set and the user has no passkey yet. A login hook can refuse the sign-in: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`.",
"description": "Answers 403 with `code: oauth_provider_retired` when an organization the user belongs to has retired this provider, and 403 `login_method_disabled` when the account has been revoked or has to sign in with a passkey (phishing-resistant-only mode, or the account holds a passkey and `passkey_login_fallback_enabled` is off). A success carries `nextStep: enroll_passkey` when the provider has `promptPasskeyEnrollment` set and the user has no passkey yet. A login hook can refuse the sign-in: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`.",
"tags": ["OAuth"],
"parameters": [
{
Expand Down
14 changes: 14 additions & 0 deletions src/controllers/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
getEnabledOAuthProviders,
getOAuthProvider,
isOidcProvider,
OAuthAccountRevokedError,
OAuthProfileError,
oauthProfileFromIdToken,
OAuthProviderRetiredError,
Expand Down Expand Up @@ -220,6 +221,19 @@ export async function finishOAuthLogin(req: RouteRequest, res: Response) {
},
});
} catch (error) {
if (error instanceof OAuthAccountRevokedError) {
await AuthEventService.log({
userId: error.userId,
type: 'oauth_login_failed',
req,
metadata: { providerId: provider.id, reason: 'account_revoked' },
});

// Answered like the other refusals of an account that may not use this method, which
// keeps the response contract and the OAuth error codes unchanged.
return res.status(403).json({ error: 'login_method_disabled' });
}

if (error instanceof OAuthProviderRetiredError) {
await AuthEventService.log({
userId: error.userId,
Expand Down
6 changes: 4 additions & 2 deletions src/controllers/webauthn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ const generateWebAuthn = async (req: Request, res: Response) => {
if (!authReq.attemptId) {
await AuthEventService.log({
userId: user.id,
type: 'login_failed',
type: 'webauthn_login_failed',
req,
metadata: { reason: 'Ephemeral token has no attempt id' },
});
Expand All @@ -480,9 +480,11 @@ const generateWebAuthn = async (req: Request, res: Response) => {
});

if (!assertionCredentials || assertionCredentials.length === 0) {
// Not a lockout failure: anyone holding a pre-auth token for the address can ask for a
// credential id the account does not have, and must not be able to lock it out by doing so.
await AuthEventService.log({
userId: user.id,
type: 'login_failed',
type: 'webauthn_login_failed',
req,
metadata: { reason: prf ? 'No PRF-capable credentials' : 'No credentials' },
});
Expand Down
2 changes: 1 addition & 1 deletion src/generated/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16572,7 +16572,7 @@ export interface paths {
put?: never;
/**
* Finish OAuth login
* @description Answers 403 with `code: oauth_provider_retired` when an organization the user belongs to has retired this provider, and 403 `login_method_disabled` when the account has to sign in with a passkey (phishing-resistant-only mode, or the account holds a passkey and `passkey_login_fallback_enabled` is off). A success carries `nextStep: enroll_passkey` when the provider has `promptPasskeyEnrollment` set and the user has no passkey yet. A login hook can refuse the sign-in: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`.
* @description Answers 403 with `code: oauth_provider_retired` when an organization the user belongs to has retired this provider, and 403 `login_method_disabled` when the account has been revoked or has to sign in with a passkey (phishing-resistant-only mode, or the account holds a passkey and `passkey_login_fallback_enabled` is off). A success carries `nextStep: enroll_passkey` when the provider has `promptPasskeyEnrollment` set and the user has no passkey yet. A login hook can refuse the sign-in: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`.
*/
post: {
parameters: {
Expand Down
38 changes: 38 additions & 0 deletions src/middleware/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,41 @@ const sessionExchangeCachedLimiter = createFlowLimiter(
export function sessionExchangeLimiter(req: Request, res: Response, next: NextFunction) {
return sessionExchangeCachedLimiter(req, res, next);
}

// Per attempt only, with no cap across one account's attempts. A pre-auth token comes from an
// address alone, so an account-wide cap is one a stranger can spend to lock the owner out of the
// sign-in. A client polls a magic link every few seconds for as long as the link lives (fifteen
// minutes); a passkey sign-in starts and finishes once, with retries for a cancelled prompt.
const MAGIC_LINK_CHECKS_PER_WINDOW_PER_ATTEMPT = 300;
const WEBAUTHN_LOGINS_PER_WINDOW_PER_ATTEMPT = 10;
// What bounds a caller minting fresh attempts. A multiple of the configured OTP per-address
// limit, so a deployment that raised that for a carrier NAT raises this with it.
export const WEBAUTHN_ADDRESS_MULTIPLIER = 10;

function getSubjectOrAddressKey(req: Request) {
return subjectKey(req) ?? `ip:${clientAddressKey(req)}`;
}

const magicLinkCheckCachedLimiter = createFlowLimiter(
() => MAGIC_LINK_CHECKS_PER_WINDOW_PER_ATTEMPT,
withAttempt(getSubjectOrAddressKey),
);
const webauthnLoginIpCachedLimiter = createFlowLimiter(
(limits) => limits.otp.perIp * WEBAUTHN_ADDRESS_MULTIPLIER,
);
const webauthnLoginIdentityCachedLimiter = createFlowLimiter(
() => WEBAUTHN_LOGINS_PER_WINDOW_PER_ATTEMPT,
withAttempt(getSubjectOrAddressKey),
);

export function magicLinkCheckLimiter(req: Request, res: Response, next: NextFunction) {
return magicLinkCheckCachedLimiter(req, res, next);
}

export function webauthnLoginIpLimiter(req: Request, res: Response, next: NextFunction) {
return webauthnLoginIpCachedLimiter(req, res, next);
}

export function webauthnLoginIdentityLimiter(req: Request, res: Response, next: NextFunction) {
return webauthnLoginIdentityCachedLimiter(req, res, next);
}
7 changes: 6 additions & 1 deletion src/routes/magicLink.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ import {
verifyMagicLink,
} from '../controllers/magicLinks.js';
import { createRouter } from '../lib/createRouter.js';
import { magicLinkEmailLimiter, magicLinkIpLimiter } from '../middleware/rateLimit.js';
import {
magicLinkCheckLimiter,
magicLinkEmailLimiter,
magicLinkIpLimiter,
} from '../middleware/rateLimit.js';
import { ErrorSchema, InternalErrorSchema, MessageSchema } from '../schemas/generic.responses.js';
import {
MagicLinkConfirmBodySchema,
Expand Down Expand Up @@ -83,6 +87,7 @@ magicLinkRouter.get(
summary: 'Poll for magic link confirmation',
decoy: decoyPollMagicLink,
tags: ['MagicLinks'],
middleware: [magicLinkCheckLimiter],

schemas: {
response: {
Expand Down
2 changes: 1 addition & 1 deletion src/routes/oauth.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ oauthRouter.post(
adapter: { issues: 'session' },
summary: 'Finish OAuth login',
description:
"Answers 403 with `code: oauth_provider_retired` when an organization the user belongs to has retired this provider, and 403 `login_method_disabled` when the account has to sign in with a passkey (phishing-resistant-only mode, or the account holds a passkey and `passkey_login_fallback_enabled` is off). A success carries `nextStep: enroll_passkey` when the provider has `promptPasskeyEnrollment` set and the user has no passkey yet. A login hook can refuse the sign-in: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`.",
"Answers 403 with `code: oauth_provider_retired` when an organization the user belongs to has retired this provider, and 403 `login_method_disabled` when the account has been revoked or has to sign in with a passkey (phishing-resistant-only mode, or the account holds a passkey and `passkey_login_fallback_enabled` is off). A success carries `nextStep: enroll_passkey` when the provider has `promptPasskeyEnrollment` set and the user has no passkey yet. A login hook can refuse the sign-in: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`.",
tags: ['OAuth'],
middleware: [oauthIpLimiter, oauthProviderLimiter],
schemas: {
Expand Down
3 changes: 3 additions & 0 deletions src/routes/webauthn.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
verifyWebAuthnRegistration,
} from '../controllers/webauthn.js';
import { createRouter } from '../lib/createRouter.js';
import { webauthnLoginIdentityLimiter, webauthnLoginIpLimiter } from '../middleware/rateLimit.js';
import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js';
import { CredentialUpdateResponseSchema } from '../schemas/credential.responses.js';
import { ErrorSchema, InternalErrorSchema } from '../schemas/generic.responses.js';
Expand Down Expand Up @@ -98,6 +99,7 @@ webauthnRouter.post(
summary: 'Start WebAuthn login',
decoy: decoyStartWebAuthnLogin,
tags: ['WebAuthn'],
middleware: [webauthnLoginIpLimiter, webauthnLoginIdentityLimiter],

schemas: {
body: WebAuthnAssertionStartSchema,
Expand All @@ -121,6 +123,7 @@ webauthnRouter.post(
summary: 'Finish WebAuthn login',
decoy: decoyFinishWebAuthnLogin,
tags: ['WebAuthn'],
middleware: [webauthnLoginIpLimiter, webauthnLoginIdentityLimiter],

schemas: {
body: WebAuthnLoginFinishSchema,
Expand Down
23 changes: 23 additions & 0 deletions src/services/oauthService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,26 @@ export class OAuthProviderRetiredError extends Error {
}
}

/**
* A revoked account signs in through no route, and OAuth was the one that did not check. An
* adapter that verifies access tokens locally would accept one minted here until it expired.
*/
export class OAuthAccountRevokedError extends Error {
readonly userId: string;

constructor(userId: string) {
super('This account cannot sign in');
this.name = 'OAuthAccountRevokedError';
this.userId = userId;
}
}

function assertNotRevoked(user: User) {
if (user.revoked) {
throw new OAuthAccountRevokedError(user.id);
}
}

async function assertProviderNotRetired(provider: OAuthProviderConfig, user: User) {
const retiring = await findOrganizationsRetiringOAuthProvider(user.id, provider.id);

Expand Down Expand Up @@ -836,6 +856,7 @@ export async function resolveOAuthUser(provider: OAuthProviderConfig, profile: O
if (existingIdentity) {
const user = await User.findByPk(existingIdentity.userId);
if (user) {
assertNotRevoked(user);
await assertProviderNotRetired(provider, user);
return user;
}
Expand All @@ -852,6 +873,7 @@ export async function resolveOAuthUser(provider: OAuthProviderConfig, profile: O

if (imported) {
// Before claiming or linking, so a refused sign-in leaves the account as it was.
assertNotRevoked(imported);
await assertProviderNotRetired(provider, imported);
await claimUnverifiedAccount(imported, profile.emailVerified === true);
await linkOAuthIdentity(provider, profile, imported);
Expand Down Expand Up @@ -881,6 +903,7 @@ export async function resolveOAuthUser(provider: OAuthProviderConfig, profile: O
}

if (user) {
assertNotRevoked(user);
await assertProviderNotRetired(provider, user);
await claimUnverifiedAccount(user, true);
} else {
Expand Down
12 changes: 12 additions & 0 deletions src/services/webauthnChallengeService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export async function issueChallenge(params: {
const now = params.now ?? new Date();

await consumeOutstanding(params.userId, params.purpose, params.attemptId, now);
await collectSpentChallenges(params.userId, now);

return WebAuthnChallenge.create({
userId: params.userId,
Expand Down Expand Up @@ -138,3 +139,14 @@ async function consumeOutstanding(
},
);
}

// A row is only read while it is live, so spent and expired ones are dropped as the user's next
// challenge is issued. Without this every ceremony start left a row behind for good.
async function collectSpentChallenges(userId: string, now: Date) {
await WebAuthnChallenge.destroy({
where: {
userId,
[Op.or]: [{ consumedAt: { [Op.ne]: null } }, { expiresAt: { [Op.lte]: now } }],
},
});
}
33 changes: 33 additions & 0 deletions tests/integration/oauth/oauth.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,39 @@ describe('OAuth routes', () => {
);
});

it('refuses a revoked account that matches by email, before claiming or linking', async () => {
const user = buildUser({ id: 'user-1', phone: null, verified: false, revoked: true });
(User.findOne as any).mockResolvedValue(user);

const res = await finishGoogleSignIn();

expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'login_method_disabled' });
expect(OAuthIdentity.findOrCreate).not.toHaveBeenCalled();
expect(user.update).not.toHaveBeenCalled();
expect(Session.create).not.toHaveBeenCalled();
expect(AuthEventService.log).toHaveBeenCalledWith(
expect.objectContaining({
type: 'oauth_login_failed',
userId: 'user-1',
metadata: expect.objectContaining({ reason: 'account_revoked' }),
}),
);
});

it('refuses a revoked account whose identity is already linked', async () => {
(OAuthIdentity.findOne as any).mockResolvedValue({ userId: 'user-1' });
(User.findByPk as any).mockResolvedValue(
buildUser({ id: 'user-1', phone: null, revoked: true }),
);

const res = await finishGoogleSignIn();

expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'login_method_disabled' });
expect(Session.create).not.toHaveBeenCalled();
});

it('refuses a returning user whose identity is already linked', async () => {
(OAuthIdentity.findOne as any).mockResolvedValue({ userId: 'user-1' });
(User.findByPk as any).mockResolvedValue(buildUser({ id: 'user-1', phone: null }));
Expand Down
75 changes: 74 additions & 1 deletion tests/integration/rateLimit/identityFlowLimits.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@ type IdentityLimiter = (req: Request, res: Response, next: NextFunction) => unkn
* Mounts one identity limiter behind a stand-in for bearer auth, which is what sets the
* user and the attempt on a real ephemeral route before route middleware runs.
*/
async function appWith(name: 'otpIdentityLimiter' | 'magicLinkEmailLimiter') {
async function appWith(
name:
| 'otpIdentityLimiter'
| 'magicLinkEmailLimiter'
| 'magicLinkCheckLimiter'
| 'webauthnLoginIdentityLimiter'
| 'webauthnLoginIpLimiter',
) {
vi.resetModules();
const limiters = await import('../../../src/middleware/rateLimit.js');
const limiter = limiters[name] as IdentityLimiter;
Expand Down Expand Up @@ -120,3 +127,69 @@ describe.each(['otpIdentityLimiter', 'magicLinkEmailLimiter'] as const)('%s', (n
expect(await status(app, 'owner@example.com', 'owner')).toBe(200);
});
});

// Fixed per-attempt allowances, not flow_rate_limits keys: a new key there needs a types release.
describe.each([
['magicLinkCheckLimiter', 300],
['webauthnLoginIdentityLimiter', 10],
] as const)('%s', (name, perAttempt) => {
it('refuses an attempt past its allowance and leaves another attempt its own', async () => {
const app = await appWith(name);

for (let i = 0; i < perAttempt; i++) {
expect(await status(app, 'owner@example.com', 'attempt-a')).toBe(200);
}

expect(await status(app, 'owner@example.com', 'attempt-a')).toBe(429);
expect(await status(app, 'owner@example.com', 'attempt-b')).toBe(200);
});

// A pre-auth token comes from an address alone, so a cap across an account's attempts is
// one a stranger can spend to keep the owner from signing in.
it("leaves the owner's attempt untouched however many attempts a stranger spends", async () => {
const app = await appWith(name);

for (let attempt = 0; attempt < 5; attempt++) {
for (let i = 0; i <= perAttempt; i++) {
await send(app, 'owner@example.com', `stranger-${attempt}`);
}
}

expect(await status(app, 'owner@example.com', 'owner')).toBe(200);
});

it('falls back to the requester address without a subject or attempt', async () => {
vi.resetModules();
const limiters = await import('../../../src/middleware/rateLimit.js');
const app = express();
app.post('/flow', limiters[name] as IdentityLimiter, (_req, res) => {
res.status(200).json({ ok: true });
});

for (let i = 0; i < perAttempt; i++) {
await request(app).post('/flow');
}

expect((await request(app).post('/flow')).status).toBe(429);
});
});

describe('webauthnLoginIpLimiter', () => {
it('caps one address across subjects at a multiple of the OTP per-address limit', async () => {
(getSystemConfig as ReturnType<typeof vi.fn>).mockResolvedValue({
flow_rate_limits: {
windowSeconds: 900,
otp: { perIp: 2, perIdentity: 5 },
magicLink: { perIp: 20, perIdentity: 5 },
oauth: { perIp: 30, perProvider: 10 },
},
});
const app = await appWith('webauthnLoginIpLimiter');

for (let i = 0; i < 20; i++) {
expect(await status(app, `user-${i}@example.com`, `attempt-${i}`)).toBe(200);
}

expect(await status(app, 'another@example.com', 'attempt-x')).toBe(429);
});
});
Loading