Repository navigation
fix(api): limit failed password logins per email #3759
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
kodiakhq
merged 5 commits into
ClickHouse:main
from
Aryainguz:aryainguz/login-rate-limit
Nov 23, 2026
+216
−1
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
eddc156
fix(api): limit failed password logins per email
Aryainguz 6fccfbd
fix(api): give the CLI a readable rate-limit message and isolate its …
Aryainguz 1b165bf
fix(api): count only rejected credentials toward the login limit
Aryainguz 3289ca2
fix(api): shorten the login lockout window and isolate the limiter tests
Aryainguz c97a2ca
Merge branch 'main' into aryainguz/login-rate-limit
Aryainguz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| '@hyperdx/api': patch | ||
| '@hyperdx/app': patch | ||
| --- | ||
|
|
||
| fix: limit failed password logins to 10 per email every 2 minutes |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import type { NextFunction, Request, Response } from 'express'; | ||
|
|
||
| import * as config from '@/config'; | ||
| import { getCounter, getServerSpan } from '@/utils/instrumentation'; | ||
| import rateLimiter from '@/utils/rateLimiter'; | ||
|
|
||
| export const LOGIN_MAX_FAILED_ATTEMPTS = 10; | ||
| // Short, because anyone who knows an email can lock that account out for this | ||
| // long. | ||
| const LOGIN_RATE_LIMIT_WINDOW_MS = 2 * 60 * 1000; | ||
|
|
||
| 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: Request) => { | ||
| const email = req.body?.email || req.query.email; | ||
| return typeof email === 'string' ? email.trim().toLowerCase() : ''; | ||
| }; | ||
|
|
||
| // 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 markRejectedLogin flags the rejection 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. | ||
| export const loginRateLimiter = rateLimiter({ | ||
| windowMs: LOGIN_RATE_LIMIT_WINDOW_MS, | ||
| max: LOGIN_MAX_FAILED_ATTEMPTS, | ||
| standardHeaders: true, | ||
| legacyHeaders: false, | ||
| skipSuccessfulRequests: true, | ||
| requestWasSuccessful: (_req, res) => res.locals.loginRejected !== 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', | ||
| message: | ||
| 'Too many failed login attempts. Please wait a few minutes and try again.', | ||
| }); | ||
| return; | ||
| } | ||
| res.redirect( | ||
| 303, | ||
| `${config.FRONTEND_REDIRECT_BASE}/login?err=tooManyAttempts`, | ||
| ); | ||
| }, | ||
| }); | ||
|
|
||
| // passport passes on wrong credentials as an AuthenticationError and server | ||
| // errors as they are. | ||
| export function markRejectedLogin( | ||
| err: Error, | ||
| _req: Request, | ||
| res: Response, | ||
| next: NextFunction, | ||
| ) { | ||
| res.locals.loginRejected = err.name === 'AuthenticationError'; | ||
| next(err); | ||
| } |
136 changes: 136 additions & 0 deletions
136
packages/api/src/routers/api/__tests__/login.int.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import { getAgent, getLoggedInAgent, getServer } from '@/fixtures'; | ||
| import { | ||
| LOGIN_MAX_FAILED_ATTEMPTS, | ||
| loginRateLimiter, | ||
| } from '@/middleware/loginRateLimiter'; | ||
| import User from '@/models/user'; | ||
|
|
||
| const MOCK_USER = { | ||
| email: 'login-limit@example.com', | ||
| password: 'TacoCat!2#4X', | ||
| }; | ||
| const OTHER_EMAIL = 'someone-else@example.com'; | ||
|
|
||
| describe('POST /login/password rate limit', () => { | ||
| const server = getServer(); | ||
| let signedInAgent: ReturnType<typeof getAgent>; | ||
|
|
||
| beforeAll(async () => { | ||
| await server.start(); | ||
| ({ agent: signedInAgent } = await getLoggedInAgent(server, MOCK_USER)); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| for (const email of [MOCK_USER.email, OTHER_EMAIL]) { | ||
| loginRateLimiter.resetKey(email); | ||
| } | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await server.stop(); | ||
| }); | ||
|
|
||
| const login = (email: string, password: string) => | ||
| getAgent(server) | ||
| .post('/login/password') | ||
| .type('form') | ||
| .send({ email, password }); | ||
|
|
||
| const failLogins = async (email: string) => { | ||
| for (let i = 0; i < LOGIN_MAX_FAILED_ATTEMPTS; i++) { | ||
| const res = await login(email, 'wrong-password'); | ||
| expect(res.headers.location).toContain('/login?err=authFail'); | ||
| } | ||
| }; | ||
|
|
||
| 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 () => { | ||
| await failLogins(MOCK_USER.email); | ||
|
|
||
| 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 () => { | ||
| await failLogins(MOCK_USER.email); | ||
| const blocked = await login(MOCK_USER.email, 'wrong-password'); | ||
| expect(blocked.headers.location).toContain('/login?err=tooManyAttempts'); | ||
|
|
||
| const other = await login(OTHER_EMAIL, 'wrong-password'); | ||
| expect(other.headers.location).toContain('/login?err=authFail'); | ||
| }); | ||
|
Aryainguz marked this conversation as resolved.
Resolved
|
||
|
|
||
| it('counts failed attempts made from a signed-in session', async () => { | ||
| for (let i = 0; i < LOGIN_MAX_FAILED_ATTEMPTS; i++) { | ||
| await signedInAgent | ||
| .post('/login/password') | ||
| .type('form') | ||
| .send({ email: OTHER_EMAIL, password: 'wrong-password' }); | ||
| } | ||
|
|
||
| const res = await login(OTHER_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: OTHER_EMAIL, password: 'wrong-password' }; | ||
| // 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('does not count server errors, such as the database being down', async () => { | ||
| 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(OTHER_EMAIL, 'wrong-password'); | ||
| expect(res.headers.location).toContain('/login?err=unknown'); | ||
| } | ||
| } finally { | ||
| findByUsername.mockRestore(); | ||
| } | ||
|
|
||
| const res = await login(OTHER_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) | ||
| .post('/login/password') | ||
| .send({ email: OTHER_EMAIL, 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.error).toBe('tooManyAttempts'); | ||
| expect(res.body.message).toMatch(/too many failed login attempts/i); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.