Harden login: rate limits, expiring tokens, no credentials in logs #3

Merged
matchu merged 1 commit from armin-bot/impress-2020:claude/codebase-security-audit-3e2fxx into main 2026-11-08 14:27:54 -08:00
Contributor

Companion to OpenNeo/impress#13, from the same security audit. That PR rate-limits Classic DTI's login form, but Impress 2020's login GraphQL mutation checks the same passwords (same openneo_id.users table), so without this, an attacker could just go around those limits.

What's wrong today

  1. Unlimited password guessing via login. Nothing limits attempts, and GraphQL aliases let one HTTP request carry hundreds of login calls ({a: login(…) b: login(…) …}), so per-request limits in nginx wouldn't help either.
  2. Auth tokens never expire on the server. getUserIdFromToken did authToken.createdAt < oneWeekAgo, comparing an ISO string to a Date. That comparison is always false ("2020-01-01T…" < new Date() → false), so the one-week expiry never fired. Browsers drop the cookie after a week, but a token copied from a cookie or a log stayed valid forever.
  3. Credentials in logs. Every successful login logged the full auth token (a bearer credential, which stayed valid forever per #2). Every failed login logged the HMAC of the attempted password. The Auth0 path logged rejected bearer tokens.

What this changes

  • Rate limits in getAuthToken: 10 attempts per account per 10 minutes, and 100 attempts overall per 10 minutes (per process, so pm2's cluster mode loosens this a few times over).
    • Keyed by account ID, not the typed username, because the utf8mb3_general_ci collation matches victim, VICTIM, Víctim… to the same row.
    • No await between checking a limit and counting the attempt, so concurrent aliased mutations can't all pass before any of them is counted.
    • Throttled attempts throw an error, so the login modal shows "Oops, login failed: There have been a lot of login attempts recently…" instead of a misleading "wrong password".
    • There's no per-IP limit, because Impress 2020 doesn't have a client IP it can trust: its nginx sets no forwarding headers, so X-Forwarded-For is entirely client-supplied.
  • Token expiry fixed: parse createdAt into a Date, and reject tokens whose date doesn't parse.
  • Logging: log user IDs instead of tokens and password hashes.
  • Small things: constant-time comparison for signatures and password hashes, and malformed tokens return null instead of throwing.

⚠️ Tradeoff to decide on

The overall limit is a deliberate tradeoff. It's the only way to slow down credential stuffing (many accounts, a few guesses each) without a trustworthy IP. But it also means someone could spam failed logins to pause Impress 2020 logins for everyone, 10 minutes at a time. Classic DTI's login isn't affected. If Impress 2020 logins barely get used anymore, that seems like a fine trade (and removing the login/createAccount mutations entirely would be even better). If they do get real use, raise the limit or drop it.

Testing

The repo's jest setup is stale (no jest dependency, and the query-tests setup dir is missing), so I didn't add tests here. Instead, I bundled the real auth-by-db.js + rate-limiter.js with esbuild, against a stub DB, and checked:

  • Login succeeds, and its token validates. Tampered, garbage, null, and non-object tokens return null without throwing.
  • An 8-day-old validly signed token is rejected, a 6-day-old one is accepted, and one with an unparseable date is rejected.
  • 12 concurrent attempts against one account, with mixed-case spellings, allow exactly the remaining budget, and the rest throw TooManyLoginAttemptsError. Even the correct password is refused while throttled.
  • The overall limit kicks in at 100 attempts, and rejects before touching the DB.
  • RateLimiter: window rollover, independent keys, and pruning of expired keys.

I haven't run it end-to-end in a full Next/MySQL environment, so a quick login on staging/prod after deploy would be good.

🤖 Generated with Claude Code

https://claude.ai/code/session_014PWWd37NNMoRcoGZrnWKEs

Companion to OpenNeo/impress#13, from the same security audit. That PR rate-limits Classic DTI's login form, but Impress 2020's `login` GraphQL mutation checks the **same passwords** (same `openneo_id.users` table), so without this, an attacker could just go around those limits. ## What's wrong today 1. **Unlimited password guessing via `login`.** Nothing limits attempts, and GraphQL aliases let one HTTP request carry hundreds of `login` calls (`{a: login(…) b: login(…) …}`), so per-request limits in nginx wouldn't help either. 2. **Auth tokens never expire on the server.** `getUserIdFromToken` did `authToken.createdAt < oneWeekAgo`, comparing an ISO **string** to a `Date`. That comparison is always `false` (`"2020-01-01T…" < new Date()` → `false`), so the one-week expiry never fired. Browsers drop the cookie after a week, but a token copied from a cookie or a log stayed valid forever. 3. **Credentials in logs.** Every successful login logged the full auth token (a bearer credential, which stayed valid forever per #2). Every failed login logged the HMAC of the attempted password. The Auth0 path logged rejected bearer tokens. ## What this changes - **Rate limits** in `getAuthToken`: 10 attempts per account per 10 minutes, and 100 attempts overall per 10 minutes (per process, so pm2's cluster mode loosens this a few times over). - Keyed by **account ID**, not the typed username, because the `utf8mb3_general_ci` collation matches `victim`, `VICTIM`, `Víctim`… to the same row. - **No `await` between checking a limit and counting the attempt**, so concurrent aliased mutations can't all pass before any of them is counted. - Throttled attempts throw an error, so the login modal shows "Oops, login failed: There have been a lot of login attempts recently…" instead of a misleading "wrong password". - There's no per-IP limit, because Impress 2020 doesn't have a client IP it can trust: its nginx sets no forwarding headers, so `X-Forwarded-For` is entirely client-supplied. - **Token expiry fixed**: parse `createdAt` into a `Date`, and reject tokens whose date doesn't parse. - **Logging**: log user IDs instead of tokens and password hashes. - **Small things**: constant-time comparison for signatures and password hashes, and malformed tokens return `null` instead of throwing. ## ⚠️ Tradeoff to decide on The **overall** limit is a deliberate tradeoff. It's the only way to slow down credential stuffing (many accounts, a few guesses each) without a trustworthy IP. But it also means someone could spam failed logins to **pause Impress 2020 logins for everyone**, 10 minutes at a time. Classic DTI's login isn't affected. If Impress 2020 logins barely get used anymore, that seems like a fine trade (and removing the `login`/`createAccount` mutations entirely would be even better). If they do get real use, raise the limit or drop it. ## Testing The repo's jest setup is stale (no `jest` dependency, and the `query-tests` setup dir is missing), so I didn't add tests here. Instead, I bundled the real `auth-by-db.js` + `rate-limiter.js` with esbuild, against a stub DB, and checked: - Login succeeds, and its token validates. Tampered, garbage, `null`, and non-object tokens return `null` without throwing. - An 8-day-old validly signed token is rejected, a 6-day-old one is accepted, and one with an unparseable date is rejected. - 12 **concurrent** attempts against one account, with mixed-case spellings, allow exactly the remaining budget, and the rest throw `TooManyLoginAttemptsError`. Even the correct password is refused while throttled. - The overall limit kicks in at 100 attempts, and rejects before touching the DB. - `RateLimiter`: window rollover, independent keys, and pruning of expired keys. I haven't run it end-to-end in a full Next/MySQL environment, so a quick login on staging/prod after deploy would be good. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_014PWWd37NNMoRcoGZrnWKEs
Impress 2020's `login` mutation checks the same passwords as Classic DTI's
login form, but nothing limited how many guesses a client could make. And
with GraphQL aliases, one request could carry hundreds of attempts! Now we
limit attempts per account (keyed by account ID, since the database treats
many spellings of a name as equivalent) and overall. We can't limit by IP
here, because we don't have a trustworthy client IP.

The checks run synchronously, with no `await` between checking the limit
and counting the attempt, so concurrent aliased mutations can't all sneak
past before any of them is counted.

Also fix `getUserIdFromToken`'s expiry check: it compared the `createdAt`
string directly to a `Date`, which is always false, so auth tokens never
expired on the server side. (Browsers drop the cookie after a week, but a
copied token stayed valid forever.) We now parse the date, and reject
tokens with a malformed one.

And some smaller things in the same spirit:
- Stop logging full auth tokens on login (they're bearer credentials), and
  the password hash of each failed attempt.
- Stop logging Auth0 bearer tokens when they fail validation.
- Compare signatures and password hashes in constant time.
- Return null for malformed tokens, rather than throwing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014PWWd37NNMoRcoGZrnWKEs
matchu approved these changes 2026-11-08 14:27:49 -08:00
matchu merged commit 3c659ac32e into main 2026-11-08 14:27:54 -08:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
OpenNeo/impress-2020!3
No description provided.