fix(api): count a sign-in attempt before checking its password [T-2597]

Merged
EV
6d ago
+387-52

What was wrong

UserService.authenticate (api/src/services/user.service.ts on develop e0acd75) read the count of failed sign-ins first (:353, getLoginAttempts), compared it with the maximum (:364), and stored a failure only after bcrypt.compare (:404, then incrementLoginAttempts at :407). With Redis that store was a SET of the value read at :353 plus 1 (:438), not an increment.

So parallel POST /api/v1/auth/token requests with wrong passwords for one account all read the count before any failure was stored, and all of them were checked: 5 parallel requests got 5 x 401 and no 429. With Redis, every parallel failure wrote the same value + 1, so a burst of 100 added only 1. With the production default of 100 sign-ins per minute per IP (TR_AUTH_THROTTLE_LIMIT, api/src/config.ts:156), that is about 100 guesses a minute per IP instead of 3 (TR_LOGIN_ATTEMPTS_MAX, :162) every 15 minutes.

What changed

  • authenticate counts the attempt before the password is checked (countLoginAttempt) and answers 429 when no attempt is left. Each count is one atomic write that returns its own result, so parallel attempts each take one of the attempts left:
    • without Redis: UPDATE user SET loginAttempts = loginAttempts + 1 WHERE id = ? AND loginAttempts < max (TypeORM increment with LessThan). No row changed means 429, and the stored count stops at the maximum.
    • with Redis: one MULTI of SET key 0 PX ttl NX and INCR key (new UserLoginAttemptsStorage.incrementUserAttempts). The key gets its expiry when it is new, and a result above the maximum means 429.
  • lastLogin moves for every attempt, refused ones too, as before. It moves just before the count: once it has moved, a sign-in that read the user earlier can no longer clear the new counts as older than the 15-minute window. That reset (clearExpiredLoginAttempts) is unchanged and still runs before the check.
  • A correct password still resets the count.
  • The 422 paths keep their counts. An account without a password still counts the attempt. A published password is right but gets removed from the account, and it gives its count back (uncountLoginAttempt), so the count stays where it was, as before. The refund never goes below 0 and never creates a count: without Redis decrement ... WHERE loginAttempts > 0, with Redis a short script that runs DECR only while the count is above 0 (decrementUserAttempts), so a count reset or expired meanwhile stays as it is. One edge is left: if the Redis key expires while a published password is being checked and new attempts start a new count meanwhile, the refund takes one attempt off that new count. That needs the account's published password, which the same request removes, so the account has no password left to guess.
  • The unsupported-grant check now runs before the count, so a grant other than password does not use up the attempts of the password sign-in (the Google path calls authenticate with provider). It still answers 400, and now also while the account is locked (before, 429 there).
  • docs/changelog.md: a line under "next".

Other changes in behaviour, all on purpose:

  • Without Redis, a refused attempt (429) no longer adds to the stored count, which stops at the maximum. The unit test "still locks the account within the window" now expects 3 instead of 4, and checks that lastLogin moved.
  • With Redis, the count is the key, and it ends when the key expires: TR_LOGIN_ATTEMPTS_TTL (15 minutes by default) after the first attempt it counts. Before, every failed or refused attempt set the key again with a new expiry, and a lastLogin older than 15 minutes made a request treat the Redis count as 0. That reset was decided on a value read before the attempt was counted, which is the race this PR closes, so Redis now relies on the expiry alone. In practice the Redis count is now a fixed window, not a rolling one: it starts at the first attempt it counts (or at the last successful sign-in, which sets it to 0 with a new expiry) and ends TR_LOGIN_ATTEMPTS_TTL later, whatever attempts come in between. So steady guessing no longer keeps the account locked, and at most 3 passwords are checked per window; up to 6 can be checked close together around the moment one window ends and the next starts. A TR_LOGIN_ATTEMPTS_TTL above 15 minutes now holds for that long.
  • With Redis, the unused loginAttempts column is no longer incremented as well. A correct password still sets it to 0.

Tests

Written first and run on develop's user.service.ts and user-login-attempts.storage.ts, then with this change.

api/src/services/user.service.spec.ts (16 tests, 12 new, 1 changed): 4 fail before (12 pass), 16/16 pass after. The Redis tests use a fake client whose MULTI runs as one step, as in Redis, and which applies expiries on a clock of its own.

  • authenticate without Redis / checks no more parallel wrong passwords than the maximum: 5 parallel wrong passwords with a slowed bcrypt.compare give exactly 3 x 401 and 2 x 429, compare runs 3 times, and the stored count is 3. Before: 5 x 401.
  • authenticate with Redis / the same test. Before: 5 x 401.
  • authenticate with Redis / unlocks once the count expires, which later attempts do not postpone: 3 failures lock the account, an attempt 1 ms before the key expires is refused and leaves the expiry as it was, and the right password works once the key has expired. Before: the refused attempt set the key again for another 15 minutes.
  • still locks the account within the window: count stays 3 and lastLogin moves. Before: 4.
  • Pass before and after, so the counts stay as they were: no password gives 422 and adds 1, a published password gives 422 and leaves the count, both with and without Redis. With Redis, the right password is refused at the maximum, and the right password after 2 failures resets the count to 0. A published password's refund stays at 0 when the count was reset meanwhile (both modes), and does not create the Redis key again once it expired.

api/test/auth.e2e-spec.ts / should check no more parallel wrong passwords than the maximum of 3: 5 parallel requests (under the e2e limit of 10 sign-ins per minute, so each 429 is the lockout) give [401, 401, 401, 429, 429]. On SQLite: fails before (5 x 401; 1 failed, 18 passed in the file), passes after.

Checks run

On Windows, Node 24, in a fresh clone:

  • yarn --cwd api lint: passes.
  • yarn check-fmt: passes.
  • API unit suite (jest --runInBand, on the first commit): 203 of 204 pass. The one failure, src/formatters/properties.spec.ts, is Windows-only and not touched here: the properties package writes \r\n on win32, so the fixture comparison fails. On Linux CI it passes.
  • API e2e suite (yarn jest --config ./test/jest-e2e.json --runInBand --forceExit, env as .github/workflows/ci.yml):
    • SQLite (better-sqlite3), whole suite on the first commit: 21 of 21 suites, 190 of 190 tests. The later commits change only the Redis branch, which e2e does not use (no Redis there), the unit tests and the changelog; on the final code auth and default-admin pass again: 25 of 25.
    • MySQL 5.7 and Postgres 15 (throwaway local containers), final code, whole suite: 21 of 21 suites and 190 of 190 tests pass on each (auth and default-admin, which sign in with passwords, in one run; the other 19 suites in a second run).
  • CircleCI test passes on the PR.

Fleet task T-2597; authored by the lead lane while the fleet is paused by its daily cost ceiling.

🤖 Generated with Claude Code