From eddc156c33cf482df52047e19ae729e198df6283 Mon Sep 17 00:00:00 2001 From: aryainguz Date: Sun, 22 Nov 2026 04:46:28 +0530 Subject: [PATCH 1/3] fix(api): limit failed password logins per email POST /login/password accepted unlimited password attempts. Failed attempts are now limited to 10 per email every 15 minutes. Successful logins don't count. The browser form is redirected to /login?err=tooManyAttempts and JSON clients get a 429. Addresses the second half of #2775. --- .changeset/login-rate-limit.md | 6 ++ .../routers/api/__tests__/login.int.test.ts | 92 +++++++++++++++++++ packages/api/src/routers/api/root.ts | 48 ++++++++++ packages/app/src/AuthPage.tsx | 4 +- 4 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 .changeset/login-rate-limit.md create mode 100644 packages/api/src/routers/api/__tests__/login.int.test.ts diff --git a/.changeset/login-rate-limit.md b/.changeset/login-rate-limit.md new file mode 100644 index 0000000000..e2f7c31ce6 --- /dev/null +++ b/.changeset/login-rate-limit.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/api': patch +'@hyperdx/app': patch +--- + +fix: limit failed password logins to 10 per email every 15 minutes diff --git a/packages/api/src/routers/api/__tests__/login.int.test.ts b/packages/api/src/routers/api/__tests__/login.int.test.ts new file mode 100644 index 0000000000..005a13f935 --- /dev/null +++ b/packages/api/src/routers/api/__tests__/login.int.test.ts @@ -0,0 +1,92 @@ +import { getAgent, getLoggedInAgent, getServer } from '@/fixtures'; +import { LOGIN_MAX_FAILED_ATTEMPTS } from '@/routers/api/root'; + +const MOCK_USER = { + email: 'login-limit@example.com', + password: 'TacoCat!2#4X', +}; + +describe('POST /login/password rate limit', () => { + const server = getServer(); + let signedInAgent: ReturnType; + + beforeAll(async () => { + await server.start(); + ({ agent: signedInAgent } = await getLoggedInAgent(server, MOCK_USER)); + }); + + afterAll(async () => { + await server.stop(); + }); + + const login = (email: string, password: string) => + getAgent(server) + .post('/login/password') + .type('form') + .send({ email, password }); + + it('does not count successful logins', async () => { + for (let i = 0; i <= LOGIN_MAX_FAILED_ATTEMPTS; i++) { + const res = await login(MOCK_USER.email, MOCK_USER.password); + expect(res.status).toBe(303); + expect(res.headers.location).not.toContain('err='); + } + }); + + it('blocks an email after too many failed attempts, even with the right password', async () => { + for (let i = 0; i < LOGIN_MAX_FAILED_ATTEMPTS; i++) { + const res = await login(MOCK_USER.email, 'wrong-password'); + expect(res.headers.location).toContain('/login?err=authFail'); + } + + const blocked = await login(MOCK_USER.email, MOCK_USER.password); + expect(blocked.status).toBe(303); + expect(blocked.headers.location).toContain('/login?err=tooManyAttempts'); + + // Emails are case-insensitive, so another spelling shares the limit. + const upper = await login(MOCK_USER.email.toUpperCase(), 'wrong-password'); + expect(upper.headers.location).toContain('/login?err=tooManyAttempts'); + }); + + it('keeps a separate limit for each email', async () => { + const res = await login('someone-else@example.com', 'wrong-password'); + expect(res.headers.location).toContain('/login?err=authFail'); + }); + + it('counts failed attempts made from a signed-in session', async () => { + const email = 'signed-in-target@example.com'; + for (let i = 0; i < LOGIN_MAX_FAILED_ATTEMPTS; i++) { + await signedInAgent + .post('/login/password') + .type('form') + .send({ email, password: 'wrong-password' }); + } + + const res = await login(email, 'wrong-password'); + expect(res.headers.location).toContain('/login?err=tooManyAttempts'); + }); + + it('limits an email sent in the query string, as passport accepts it there', async () => { + const query = { email: 'query-target@example.com', password: 'wrong' }; + // A new X-Forwarded-For each time, so falling back to req.ip can't limit it. + const attempt = (i: number) => + getAgent(server) + .post('/login/password') + .set('X-Forwarded-For', `10.0.0.${i}`) + .query(query); + for (let i = 0; i < LOGIN_MAX_FAILED_ATTEMPTS; i++) { + await attempt(i); + } + + const res = await attempt(LOGIN_MAX_FAILED_ATTEMPTS); + expect(res.headers.location).toContain('/login?err=tooManyAttempts'); + }); + + it('answers JSON clients such as the CLI with a 429', async () => { + const res = await getAgent(server) + .post('/login/password') + .send({ email: MOCK_USER.email, password: 'wrong-password' }); + expect(res.status).toBe(429); + expect(res.body).toEqual({ error: 'tooManyAttempts' }); + }); +}); diff --git a/packages/api/src/routers/api/root.ts b/packages/api/src/routers/api/root.ts index 220ba6f27b..7ef64cdc0d 100644 --- a/packages/api/src/routers/api/root.ts +++ b/packages/api/src/routers/api/root.ts @@ -10,11 +10,54 @@ import { handleAuthError, redirectToDashboard } from '@/middleware/auth'; import TeamInvite from '@/models/teamInvite'; import User from '@/models/user'; // TODO -> do not import model directly import { setupTeamDefaults } from '@/setupDefaults'; +import { getCounter, getServerSpan } from '@/utils/instrumentation'; import logger from '@/utils/logger'; import passport from '@/utils/passport'; +import rateLimiter from '@/utils/rateLimiter'; import { isMongoConnected, mongoReadyStateName } from '@/utils/readiness'; import { passwordSchema } from '@/utils/validators'; +export const LOGIN_MAX_FAILED_ATTEMPTS = 10; + +const loginRateLimitedCounter = getCounter('hyperdx.api.login.rate_limited', { + description: + 'Count of password logins refused because the email had too many recent failed attempts.', +}); + +// passport-local reads the email from the body, then the query string. +const getLoginEmail = (req: express.Request) => { + const email = req.body?.email || req.query.email; + return typeof email === 'string' ? email.trim().toLowerCase() : ''; +}; + +// Only failed logins count. Success and failure both answer 303, and req.user +// is already set for a signed-in session, so success is marked on the route +// after passport accepts the password. The key is the email, not the IP: behind +// the app's /api proxy, req.ip is the proxy or whatever X-Forwarded-For the +// client sends. +const loginRateLimiter = rateLimiter({ + windowMs: 15 * 60 * 1000, + max: LOGIN_MAX_FAILED_ATTEMPTS, + standardHeaders: true, + legacyHeaders: false, + skipSuccessfulRequests: true, + requestWasSuccessful: (_req, res) => res.locals.loginSucceeded === true, + keyGenerator: req => getLoginEmail(req) || req.ip || 'unknown', + handler: (req, res) => { + loginRateLimitedCounter.add(1); + getServerSpan()?.setAttribute('hyperdx.login.rate_limited', true); + // The app's login page submits a form; the CLI posts JSON. + if (req.is('application/json')) { + res.status(429).json({ error: 'tooManyAttempts' }); + return; + } + res.redirect( + 303, + `${config.FRONTEND_REDIRECT_BASE}/login?err=tooManyAttempts`, + ); + }, +}); + const registrationSchema = z .object({ email: z.string().email(), @@ -70,10 +113,15 @@ router.get('/installation', async (_, res: InstallationEspRes, next) => { router.post( '/login/password', + loginRateLimiter, passport.authenticate('local', { failWithError: true, failureMessage: true, }), + (_req, res, next) => { + res.locals.loginSucceeded = true; + next(); + }, redirectToDashboard, handleAuthError, ); diff --git a/packages/app/src/AuthPage.tsx b/packages/app/src/AuthPage.tsx index 047a4bbab1..5ed177393e 100644 --- a/packages/app/src/AuthPage.tsx +++ b/packages/app/src/AuthPage.tsx @@ -233,7 +233,9 @@ export default function AuthPage({ action }: { action: 'register' | 'login' }) { ? 'Password authentication is not allowed by your team admin.' : err === 'teamAlreadyExists' ? 'Team already exists, please login instead.' - : 'Unknown error occurred, please try again later.'} + : err === 'tooManyAttempts' + ? 'Too many failed login attempts. Please wait a few minutes and try again.' + : 'Unknown error occurred, please try again later.'} )} From 6fccfbde9a4d2b04d8628bbf6030ffa6496742a7 Mon Sep 17 00:00:00 2001 From: aryainguz Date: Sun, 22 Nov 2026 04:59:22 +0530 Subject: [PATCH 2/3] fix(api): give the CLI a readable rate-limit message and isolate its test --- .../src/routers/api/__tests__/login.int.test.ts | 15 +++++++++++---- packages/api/src/routers/api/root.ts | 6 +++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/api/src/routers/api/__tests__/login.int.test.ts b/packages/api/src/routers/api/__tests__/login.int.test.ts index 005a13f935..ac7ae5b049 100644 --- a/packages/api/src/routers/api/__tests__/login.int.test.ts +++ b/packages/api/src/routers/api/__tests__/login.int.test.ts @@ -83,10 +83,17 @@ describe('POST /login/password rate limit', () => { }); it('answers JSON clients such as the CLI with a 429', async () => { - const res = await getAgent(server) - .post('/login/password') - .send({ email: MOCK_USER.email, password: 'wrong-password' }); + const attempt = () => + getAgent(server) + .post('/login/password') + .send({ email: 'json-client@example.com', password: 'wrong-password' }); + for (let i = 0; i < LOGIN_MAX_FAILED_ATTEMPTS; i++) { + await attempt(); + } + + const res = await attempt(); expect(res.status).toBe(429); - expect(res.body).toEqual({ error: 'tooManyAttempts' }); + expect(res.body.error).toBe('tooManyAttempts'); + expect(res.body.message).toMatch(/too many failed login attempts/i); }); }); diff --git a/packages/api/src/routers/api/root.ts b/packages/api/src/routers/api/root.ts index 7ef64cdc0d..3f3d4a1d5e 100644 --- a/packages/api/src/routers/api/root.ts +++ b/packages/api/src/routers/api/root.ts @@ -48,7 +48,11 @@ const loginRateLimiter = rateLimiter({ getServerSpan()?.setAttribute('hyperdx.login.rate_limited', true); // The app's login page submits a form; the CLI posts JSON. if (req.is('application/json')) { - res.status(429).json({ error: 'tooManyAttempts' }); + res.status(429).json({ + error: 'tooManyAttempts', + message: + 'Too many failed login attempts. Please wait a few minutes and try again.', + }); return; } res.redirect( From 1b165bf0f278c7baab29df72f66060c486ddd359 Mon Sep 17 00:00:00 2001 From: aryainguz Date: Sun, 22 Nov 2026 05:06:26 +0530 Subject: [PATCH 3/3] fix(api): count only rejected credentials toward the login limit --- .../routers/api/__tests__/login.int.test.ts | 21 +++++++++++++++ packages/api/src/routers/api/root.ts | 27 ++++++++++++------- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/packages/api/src/routers/api/__tests__/login.int.test.ts b/packages/api/src/routers/api/__tests__/login.int.test.ts index ac7ae5b049..a8f9ac9c5a 100644 --- a/packages/api/src/routers/api/__tests__/login.int.test.ts +++ b/packages/api/src/routers/api/__tests__/login.int.test.ts @@ -1,4 +1,5 @@ import { getAgent, getLoggedInAgent, getServer } from '@/fixtures'; +import User from '@/models/user'; import { LOGIN_MAX_FAILED_ATTEMPTS } from '@/routers/api/root'; const MOCK_USER = { @@ -82,6 +83,26 @@ describe('POST /login/password rate limit', () => { expect(res.headers.location).toContain('/login?err=tooManyAttempts'); }); + it('does not count server errors, such as the database being down', async () => { + const email = 'outage@example.com'; + const findByUsername = jest + .spyOn(User, 'findByUsername') + .mockImplementation(() => { + throw new Error('database unavailable'); + }); + try { + for (let i = 0; i <= LOGIN_MAX_FAILED_ATTEMPTS; i++) { + const res = await login(email, 'wrong-password'); + expect(res.headers.location).toContain('/login?err=unknown'); + } + } finally { + findByUsername.mockRestore(); + } + + const res = await login(email, 'wrong-password'); + expect(res.headers.location).toContain('/login?err=authFail'); + }); + it('answers JSON clients such as the CLI with a 429', async () => { const attempt = () => getAgent(server) diff --git a/packages/api/src/routers/api/root.ts b/packages/api/src/routers/api/root.ts index 3f3d4a1d5e..2ed79d8074 100644 --- a/packages/api/src/routers/api/root.ts +++ b/packages/api/src/routers/api/root.ts @@ -30,18 +30,18 @@ const getLoginEmail = (req: express.Request) => { return typeof email === 'string' ? email.trim().toLowerCase() : ''; }; -// Only failed logins count. Success and failure both answer 303, and req.user -// is already set for a signed-in session, so success is marked on the route -// after passport accepts the password. The key is the email, not the IP: behind -// the app's /api proxy, req.ip is the proxy or whatever X-Forwarded-For the -// client sends. +// Only rejected credentials count, not server errors such as the database being +// down. Every outcome answers 303, and req.user is already set for a signed-in +// session, so the rejection is marked on the route instead. The key is the +// email, not the IP: behind the app's /api proxy, req.ip is the proxy or +// whatever X-Forwarded-For the client sends. const loginRateLimiter = rateLimiter({ windowMs: 15 * 60 * 1000, max: LOGIN_MAX_FAILED_ATTEMPTS, standardHeaders: true, legacyHeaders: false, skipSuccessfulRequests: true, - requestWasSuccessful: (_req, res) => res.locals.loginSucceeded === true, + requestWasSuccessful: (_req, res) => res.locals.loginRejected !== true, keyGenerator: req => getLoginEmail(req) || req.ip || 'unknown', handler: (req, res) => { loginRateLimitedCounter.add(1); @@ -122,11 +122,18 @@ router.post( failWithError: true, failureMessage: true, }), - (_req, res, next) => { - res.locals.loginSucceeded = true; - next(); - }, redirectToDashboard, + // passport passes on wrong credentials as an AuthenticationError and server + // errors as they are. + ( + err: Error, + _req: express.Request, + res: express.Response, + next: express.NextFunction, + ) => { + res.locals.loginRejected = err.name === 'AuthenticationError'; + next(err); + }, handleAuthError, );