Skip to content

fix(api): limit failed password logins per email - #3759

Open
Aryainguz wants to merge 5 commits into
ClickHouse:mainfrom
Aryainguz:aryainguz/login-rate-limit
Open

Aryainguz wants to merge 5 commits into
ClickHouse:mainfrom
Aryainguz:aryainguz/login-rate-limit

Conversation

@Aryainguz

@Aryainguz Aryainguz commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Addresses the second half of #2775. POST /login/password had no rate limit, so password guessing was unlimited. #2781 fixed the first half.

  • Failed logins are limited to 10 per email every 2 minutes. Only rejected credentials count, not successful logins or server errors (e.g. the database being down).
  • Once limited, the login page shows "Too many failed login attempts…". JSON clients (the CLI) get a 429.
  • The limit is keyed on the email, not the IP. Behind the app's /api proxy, req.ip comes from X-Forwarded-For, which the client can set.

Known trade-offs

  • Lockout: anyone who knows an email can keep that account locked out of password login. Letting the right password through would let guessing continue, and there is no trusted client IP behind the /api proxy to key on. Restarting the API clears the counters.
  • Password spraying: each email gets its own 10 tries.
  • Per instance: the store is in memory, like the /api/v2 and /mcp limiters.
  • Hard-coded limits: like the MCP limiter. @pulpdrew happy to make them configurable.

Screenshots or video

Before After
image image

/login?err=tooManyAttempts

How to reproduce

Starting point: yarn dev. Set API to the API URL it prints. Any email works, no user needed.

On main:

  1. for i in $(seq 11); do curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -X POST $API/login/password -d 'email=a@example.com&password=wrong'; done
  2. All 11 attempts redirect to /login?err=authFail.

On this branch:

  1. Run the same loop. Attempts 1–10 redirect to /login?err=authFail, and the 11th to /login?err=tooManyAttempts.
  2. make dev-int FILE=login.int runs the new integration tests.

References

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 ClickHouse#2775.
@Aryainguz
Aryainguz requested a review from a team as a code owner November 21, 2026 23:24
@changeset-bot

changeset-bot Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c97a2ca

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@hyperdx/api Patch
@hyperdx/app Patch
@hyperdx/otel-collector Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel

vercel Bot commented Nov 21, 2026

Copy link
Copy Markdown

@Aryainguz is attempting to deploy a commit to the HyperDX Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

PR Review

✅ No issues found.

@Aryainguz

Aryainguz commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

3 finding(s): 🔴 1 P0/P1 · 🟡 2 P2 · 🔵 0 P3

None could be anchored to changed lines; they are listed below.

Findings outside the changed lines

  • 🔴 P1 packages/api/src/routers/api/root.ts:151 — Anyone who knows a user's email can lock that user out of password login, with no IP or credential factor → The limiter key is only the normalized email, and once a key goes over the limit the handler refuses the correct password too (the test at login.int.test.ts:54 checks this). That means an unauthenticated client can send 10 wrong passwords every 15 minutes and keep any account locked out indefinitely, including the team admin's. An admin in a password-only setup then has no way back in. Suggested fix: keep the hard block for (email, client IP), and use a separate, much higher per-email limit (or a delay) as the backstop against distributed guessing. Alternatively, make the limits configurable as the PR description offers, so operators can tune this. At minimum, document the lockout trade-off.
  • 🟡 P2 packages/api/src/routers/api/root.ts:157 — The CLI shows the raw code 'tooManyAttempts' to the user instead of a readable message → packages/cli/src/api/client.ts:163 builds its message from json.message || json.error, so the user sees Login failed (HTTP 429): tooManyAttempts. Add a message field to the 429 body, e.g. { error: 'tooManyAttempts', message: 'Too many failed login attempts. Please wait a few minutes and try again.' }.
  • 🟡 P2 packages/api/src/routers/api/__tests__/login.int.test.ts:103 — The JSON 429 test only passes if an earlier test already blocked MOCK_USER.email → This test sends one wrong password and expects a 429. That only works because the test at line 54 has already used up MOCK_USER.email's limit. Run on its own, or after the tests are reordered, the request gets a 303 authFail and the test fails. Make it self-contained: use its own email, send LOGIN_MAX_FAILED_ATTEMPTS failed JSON attempts first, then assert that the next one gets the 429 and JSON body.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

P1 here is the trade-off.

An (email, IP) key can be bypassed here: req.ip comes from X-Forwarded-For, which the client sets, and the default docker-compose.yml publishes the API port, so the app proxy can be skipped too. The test "limits an email sent in the query string" sends a new X-Forwarded-For on every attempt; the email key still blocks it, but an IP key wouldn't. A higher per-email backstop would allow the same lockout, just after more attempts, while giving more guesses. A temporary lockout seemed better than unlimited guessing.

Better options would be a trusted client IP (proxy settings plus not exposing the API port), or a CAPTCHA or email unlock link. @pulpdrew happy to make the limits configurable or take on any of these as a follow-up, let me know what you think.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found.

The change is well-constructed: the happy path is correct (successful logins are skipped via skipSuccessfulRequests + requestWasSuccessful), server errors are excluded from the count (confirmed by the DB-down test), the limiter runs before passport so it cannot be bypassed, and the prior round of review feedback (2-minute window, named window constant, dedicated middleware file, rejected-credentials-only counting, readable CLI message, same-test separate-counter proof, resetKey in afterEach for test isolation) is addressed in the current diff. No P0/P1 defect is introduced.

🟡 P2 -- recommended

  • packages/api/src/middleware/loginRateLimiter.ts:35 -- The limiter key is the email alone, and once the window fills the max check blocks even the correct password, so anyone who knows an email can hold that account out of password login for each 2-minute window indefinitely.
    • Fix: Document the account-lockout trade-off at the call site and track a follow-up to add a trusted-IP or credential factor (or configurable limits) so a known email cannot be used to sustain a targeted lockout.
  • packages/api/src/routers/api/root.ts:82 -- The limiter's requestWasSuccessful depends on res.locals.loginRejected, which is set only by markRejectedLogin running as a 4-arg error handler positioned after redirectToDashboard; reordering this chain or a change in passport's error surface would silently make the limiter over-count server errors or stop counting failures, with no test guarding the ordering contract.
    • Fix: Add a comment at the route documenting why markRejectedLogin must sit between redirectToDashboard and handleAuthError, and consider asserting the ordering invariant so a future refactor cannot silently disable the limiter.
🔵 P3 nitpicks (4)
  • packages/api/src/middleware/loginRateLimiter.ts:35 -- The default in-memory store is keyed on arbitrary unauthenticated email input, so a burst of distinct email values inflates memory until the per-window reap clears them.
    • Fix: Note the key-space exposure, or bound it (cap distinct keys or fall back to an IP-scoped key) if memory under attack traffic is a concern.
  • packages/api/src/middleware/loginRateLimiter.ts:40 -- Response shape is chosen by req.is('application/json'), so a programmatic client that omits or mismatches Content-Type receives a 303 redirect instead of the 429 JSON and never sees the structured tooManyAttempts body.
    • Fix: Fall back to the JSON 429 for non-browser clients (e.g. absence of an HTML Accept) rather than keying solely on the request content type.
  • packages/api/src/middleware/loginRateLimiter.ts:63 -- Distinguishing rejected credentials from server errors via the string err.name === 'AuthenticationError' is brittle against a passport version or failure-path change, which would flip server errors into counted failures (false lockouts) or drop real failures (limiter disabled).
    • Fix: Guard the classification with an instanceof check or a shared constant, keeping the DB-down test that currently covers this path.
  • packages/api/src/routers/api/__tests__/login.int.test.ts:1 -- No test covers window expiry (the counter clearing after the 2-minute window), so a regression that changed or dropped windowMs would go uncaught.
    • Fix: Add a fake-timer test advancing past LOGIN_RATE_LIMIT_WINDOW_MS and asserting a subsequent failed attempt redirects to authFail again.

Reviewers (11): correctness, security, adversarial, reliability, testing, maintainability, project-standards, kieran-typescript, api-contract, previous-comments, learnings.

Testing gaps: No coverage for window-expiry reset; no coverage for the req.ip/unknown fallback key when the email is absent.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

Comment thread packages/api/src/routers/api/root.ts Resolved
Comment thread packages/api/src/routers/api/root.ts Resolved
Comment thread packages/api/src/routers/api/root.ts Resolved
Comment thread packages/api/src/routers/api/root.ts Resolved
@Aryainguz
Aryainguz requested a review from pulpdrew November 23, 2026 12:51

@pulpdrew pulpdrew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants