Broken authentication: how sign-up, login and password reset flows give accounts away
Broken authentication is any flaw that lets someone be accepted as a user they are not, or brings them closer to it.
This guide walks through the five flows a sign-in system is made of: registration, login, password recovery, email change and reauthentication before a sensitive action. It shows what each one leaks or lets through when it is built carelessly, with account enumeration as the worked example, and comes with a test pack for your own application and a Node.js lab that measures the timing leak and its fix.
In this guide
Authentication flow test pack and enumeration lab
An illustration on invented accounts. Part 1 is a test pack for registration, login, password recovery, email change and reauthentication: for each test, what to send, what a safe system does, what a flawed one reveals or allows, the evidence to keep and the source behind the expected behaviour.
How to use itHide the instructions
Parts 2 to 6 are a Node.js lab with no installs: a sign-in service in a flawed and a fixed version, a script that shows each flow's answers, a timing script with real output, and a regression test that fails on the flawed version. For an application you own or are authorised in writing to test.
authentication-failures.txt
Introduction4 lines
Part 1: The authentication flow test pack251 lines
Part 2: The lab files737 lines
Part 3: What each flow tells an outsider73 lines
Part 4: The timing gap and its removal41 lines
Part 5: The regression test121 lines
Part 6: Point the tests at your own application6 lines
Whole template1,268 lines
AUTHENTICATION FLOW TEST PACK AND ENUMERATION LAB
An illustration, for testing an application you own or are authorised in writing to test.
Written and run on: Node.js 26.0.0 on an Apple M3 Max machine (macOS, arm64). The lab uses only built-in modules, which Node.js identifies with the node: prefix: node:http, node:crypto, node:test and node:assert. The Node.js documentation describes built-in modules as compiled into the binary, so there is nothing to install. Every output below was copied from that run by a script; timings and ports will differ on your machine. The accounts, passwords and example.com addresses are invented, and the lab talks only to its own server on 127.0.0.1.
================================================================
PART 1: THE AUTHENTICATION FLOW TEST PACK
Who it is for. Run these tests only on an application you own, or one you are authorised in writing to test, and only with test accounts created for the purpose. Use a staging copy where you have one. Nothing here is for probing a sign-in, sign-up or reset form that belongs to someone else.
What you need:
Account A a test account with a password and an inbox you control.
Account B a second test account with an inbox you control.
Address C an address at a domain you control that has no account.
Account M a test account with multi-factor sign-in turned on, if your application offers it.
Account L a test account the rules of engagement say may be locked, for test L3 only.
A way to read whole responses (status, headers and body), such as the Network panel in your browser's developer tools.
For the timing rows, measure-timing.mjs from Part 2, changed to send to your own staging address (see Part 6).
Evidence to keep for every test: the request as sent, with passwords redacted; the whole response (status, the Location and Set-Cookie headers, and the body); the time; the test account used; and the build or commit tested. For a timing row, also keep the number of requests, the median, middle half and range for each case, the machine and network path you measured from, and the date.
How to read a row. Send is what to do. Safe is the behaviour the named sources ask for. Flawed is what a careless build reveals or allows. Basis names the source for the safe behaviour. Where a row says no source names a check, the check is this pack's own suggestion.
Source names used in the rows:
Auth CS OWASP Authentication Cheat Sheet
Forgot CS OWASP Forgot Password Cheat Sheet
Storage CS OWASP Password Storage Cheat Sheet
WSTG-IDNT-02 OWASP WSTG v4.2, Test User Registration Process
WSTG-IDNT-04 OWASP WSTG v4.2, Testing for Account Enumeration and Guessable User Account
WSTG-ATHN-09 OWASP WSTG v4.2, Testing for Weak Password Change or Reset Functionalities
WSTG-ATHN-10 OWASP WSTG v4.2, Testing for Weaker Authentication in Alternative Channel
ASVS OWASP ASVS 5.0.0, with each requirement's level: L1, L2 or L3
A07:2025 OWASP Top 10:2025, A07 Authentication Failures
API2:2023 OWASP API Security Top 10 2023, API2 Broken Authentication
CWE MITRE CWE-204, CWE-208, CWE-620 and CWE-640
SP 800-63B-4 NIST SP 800-63B-4 (July 2025), with its section number and its own SHALL and SHOULD
Node crypto Node.js documentation, crypto module
Timing rule of thumb used in this pack: send each pair at least 25 times, alternating which goes first. Treat a pair as consistent when each median sits inside the other case's middle half. This is the pack's own rule, not a standard.
FLOW 1: REGISTRATION
R1 Same answer for an address with an account and one without
Send: sign up with A's address, then with C, using the same new password.
Safe: the same status, message and Location header for both, and no session cookie for either. Auth CS gives "A link to activate your account has been emailed to the address provided." as a correct reply for account creation.
Flawed: a 409, a message such as "This user ID is already in use." (an Auth CS incorrect example), a redirect to the sign-in page, or a session cookie for the new address only.
Evidence: both responses, side by side.
Basis: Auth CS, Authentication Responses; A07:2025; ASVS 6.3.8 (L3); WSTG-IDNT-04.
R2 Same time for both
Send: the R1 pair, repeated and alternated as the timing rule says, with a fresh address for C each time.
Safe: consistent by the timing rule.
Flawed: one case is reliably slower, for example because only a new address has its password hashed, or because the server waits for an email to send before it answers.
Evidence: the timing figures listed above.
Basis: Auth CS, on processing time that differs by case; CWE-208; ASVS 6.3.8 (L3).
R3 The address is confirmed before the account works
Send: sign up with C, then try to sign in as C before opening the email.
Safe: sign-in fails until the link sent to C is followed.
Flawed: the account works at once, so anyone can register an address they do not own.
Evidence: the sign-in response and the email C received.
Basis: Auth CS, Usernames (email as username, provided the email is verified during sign-up); WSTG-IDNT-02 (are registered identities verified?).
R4 The inbox carries the difference, not the page
Send: after R1, read A's inbox and C's inbox.
Safe: C receives the link to finish signing up. A receives a note that someone tried to sign up with the address, with links to sign in or reset the password. No source names this note; it is one way to keep R1's identical reply while still telling the owner what happened.
Flawed: the page itself says the account exists, which fails R1.
Evidence: both emails.
Basis: this pack's own suggestion; Auth CS discusses the usability cost of generic messages.
R5 Password rules at sign-up
Send: a 7-character password; a 64-character passphrase with spaces and letters outside English; a password from a common-password list.
Safe: the 7-character password is refused; the passphrase is accepted in full; the common password is refused, with the reason.
Flawed: the short password is accepted, the passphrase is cut short or refused, or a common password goes through.
Evidence: each response.
Basis: ASVS 6.2.1 (L1: at least 8 characters, 15 strongly recommended); SP 800-63B-4 3.1.1.2 (SHALL require at least 15 characters for a password used on its own, and at least 8 when it is used only as part of multi-factor authentication); ASVS 6.2.9 (L2: at least 64 characters permitted); ASVS 6.2.5 (L1: no composition rules); ASVS 6.2.4 (L1: checked against at least the top 3000 passwords that match the application's password policy, such as its minimum length); SP 800-63B-4 3.1.1.2 (SHALL compare against a blocklist and SHALL give the reason for rejection). Breached-password checks are covered in the credential stuffing guide.
FLOW 2: LOGIN
L1 One answer for a wrong password and an unknown address
Send: A's address with a wrong password; C with any password.
Safe: identical status, message, Location header and cookies. Auth CS gives "Login failed; Invalid user ID or password." as a correct reply.
Flawed: "Incorrect password" for A and "No account" for C; a 401 for one and a 404 for the other; a redirect to sign-up for C. Auth CS also warns that a 200 for one case and a 403 for the other can leak whether the account is valid, even behind an identical page.
Evidence: both responses, side by side.
Basis: Auth CS, Authentication Responses and Error Codes and URLs; WSTG-IDNT-04; CWE-204; ASVS 6.3.8 (L3).
L2 Same time for both
Send: the L1 pair, repeated and alternated as the timing rule says.
Safe: consistent by the timing rule. The server checks the password for an unknown address too, against a dummy record, as the lab's fixed version does.
Flawed: the known address is slower by about one password hash. Auth CS calls this the quick exit: the application returns an error at once when the user does not exist and does more processing when it does.
Evidence: the timing figures listed above.
Basis: Auth CS; CWE-208; ASVS 6.3.8 (L3); Node crypto (crypto.timingSafeEqual compares in constant time, and using it does not make the surrounding code timing-safe).
L3 Locked and disabled accounts look like any other failure
Send: on account L only, where the rules of engagement allow it, trigger your lockout, then send L's right password and a wrong one. Repeat with a disabled test account if your application has them.
Safe: the same generic failure as L1.
Flawed: "account locked" or "account disabled". Auth CS lists "Login failed; account disabled." among its incorrect examples.
Evidence: the responses, and how the account was unlocked afterwards.
Basis: Auth CS (a generic message whether or not the account is locked or disabled). How many attempts trigger a lock is covered in the rate limiting guide.
L4 The whole password is checked
Send: set A's password to a 100-character passphrase, then sign in with only its first 72 characters, and again with its first 64.
Safe: both refused.
Flawed: either accepted, which means the password is cut short before it is checked.
Evidence: both responses.
Basis: ASVS 6.2.8 (L1: verified exactly as received, without truncation or case changes); SP 800-63B-4 3.1.1.2 (SHALL verify the entire submitted password); Auth CS (do not silently truncate); Storage CS (the 72-byte input limit of most bcrypt implementations).
L5 How passwords are stored
Send: nothing. Read the code, or ask the developer, which password hashing function and settings are used.
Safe: Argon2id with 19 MiB of memory, an iteration count of 2 and 1 degree of parallelism, or another Argon2id row Storage CS lists as giving an equal level of defence; or, where Argon2id is not available, scrypt with N=2^17, r=8, p=1, or another scrypt row it lists; bcrypt only in a legacy system where Argon2 and scrypt are not available, with a work factor of 10 or more and a 72-byte password limit; or PBKDF2 with 600,000 or more iterations of HMAC-SHA-256 where FIPS-140 compliance is required. Each password salted, with a salt of at least 32 bits.
Flawed: a fast hash such as SHA-256, no salt, or passwords stored so they can be decrypted.
Evidence: the function, its settings and where they are configured.
Basis: Storage CS, as read on 14 November 2026 (check it again before you choose, because the numbers change); SP 800-63B-4 3.1.1.2 (SHALL be salted and hashed; salt SHALL be at least 32 bits); ASVS 11.4.2 (L2).
L6 Every other way in gets the same checks
Send: repeat L1 and L2 on each other sign-in path that shares the same accounts: a mobile app's API, a partner site, an older version of the login form, a staging copy.
Safe: the same answers and timing as the main form.
Flawed: one path still says "no such user", or skips the hash.
Evidence: the list of paths found, and L1 and L2 evidence for each.
Basis: WSTG-ATHN-10; ASVS 6.3.4 (L2: where an application has more than one authentication pathway, none undocumented and controls enforced consistently); API2:2023 (know all the possible flows to authenticate).
FLOW 3: PASSWORD RECOVERY
P1 Same answer for a registered and an unregistered address
Send: a reset request for A, then for C.
Safe: the same status and message. Auth CS gives "If that email address is in our database, we will send you an email to reset your password." as a correct reply.
Flawed: "We just sent you a password reset link." for A and "This email address doesn't exist in our database." for C (both Auth CS incorrect examples), or a masked address shown for A only.
Evidence: both responses, side by side.
Basis: Auth CS; Forgot CS; WSTG-IDNT-04 (messages from a recovery facility); A07:2025.
P2 Same time for both
Send: the P1 pair, repeated and alternated as the timing rule says.
Safe: consistent by the timing rule: the email is sent after the reply, or the same logic runs either way.
Flawed: A's reply waits for the email to send. WSTG-IDNT-04 notes that a request which calls an external service, such as sending a forgotten-password email, can add several hundred milliseconds.
Evidence: the timing figures listed above.
Basis: Forgot CS (asynchronous calls, or the same logic instead of a quick exit); WSTG-IDNT-04; CWE-208.
P3 The link works once, for one account, for a limited time
Send: use A's reset link twice. On staging, use a link after its lifetime has passed. Then request two links for A and try the older one (no source names this last check).
Safe: the second use, the expired link and the older link are refused.
Flawed: any of them still sets a password.
Evidence: each response, with the time each link was issued and used.
Basis: Forgot CS (linked to an individual user, invalidated after use, single use, expire after an appropriate period); SP 800-63B-4 4.2.1.2 (issued recovery codes sent to an email address SHALL be valid for at most 24 hours).
P4 The token is hard to guess and stored safely
Send: request several links for A and compare the tokens; ask how tokens are stored.
Safe: long random tokens with no visible pattern, stored securely as Forgot CS asks. The lab keeps only a SHA-256 hash of each token.
Flawed: tokens that count up, contain the email address or a timestamp, or sit in the database as written.
Evidence: the tokens compared (from test accounts only) and the storage code.
Basis: Forgot CS (cryptographically secure random number generator, long enough to resist brute force, stored securely); ASVS 11.5.1 (L2: CSPRNG, at least 128 bits of entropy).
P5 The link points at your domain, and the reset page leaks nothing
Send: on staging, a reset request for A with the Host header changed to a domain you control; then open the reset page and read its response headers.
Safe: the emailed link still uses your configured domain over HTTPS, and the reset page sends Referrer-Policy: no-referrer.
Flawed: the link uses the Host you sent, so a reset email could carry someone else's domain.
Evidence: the request, the email received and the reset page's headers.
Basis: Forgot CS (hard-code the URL or validate it against trusted domains; HTTPS; Referrer Policy no-referrer).
P6 Finishing a reset
Send: complete a reset for A.
Safe: A gets an email saying the password changed, without the password in it; the user is not signed in automatically and signs in through the usual form; the user is offered the option to end other sessions, or they are ended.
Flawed: the reset signs the user straight in, or nothing tells the owner.
Evidence: the final response and the email.
Basis: Forgot CS; SP 800-63B-4 4.2.3 (account recovery SHALL cause a notification); ASVS 7.4.3 (L2: the option to end other sessions after a password change via reset). Sessions are covered in the session management guide.
P7 Reset does not skip a second factor
Send: reset the password for M, then sign in as M.
Safe: the second factor is still asked for.
Flawed: the reset signs M in with the password alone, or turns the second factor off.
Evidence: each step's response.
Basis: ASVS 6.4.3 (L2). Second-factor recovery is covered in the MFA security guide.
P8 Repeated requests and secret questions
Send: several reset requests for A in a row; look for secret questions or hints anywhere in the flow.
Safe: a per-account limit stops A's inbox being flooded, A is not locked out by reset requests, and there are no secret questions or password hints.
Flawed: unlimited emails, an account locked by reset requests, or a question such as a first pet's name.
Evidence: the responses and the count of emails A received.
Basis: Forgot CS (per-account rate limiting or a CAPTCHA; no lockout in response to a forgotten password attack); API2:2023 (recovery endpoints get the same brute force, rate limiting and lockout protections as login); ASVS 6.4.2 (L1: no password hints or secret questions); A07:2025 (knowledge-based answers cannot be made safe).
FLOW 4: EMAIL CHANGE
E1 The current password, or a fresh sign-in, comes first
Send: signed in as B, change B's address with no current password, then with a wrong one.
Safe: both refused, and B's address unchanged.
Flawed: the address changes.
Evidence: both responses and B's account page afterwards.
Basis: Auth CS (require re-authentication for sensitive features; the email change process asks for the current password, or for MFA where it is on); ASVS 7.5.1 (L2); API2:2023, second example scenario; CWE-620.
E2 The new address must confirm, and the current one is told
Send: signed in as B, with the current password, change to a new address at your domain; read both inboxes before following any link.
Safe: nothing changes until the new address confirms through a time-limited link, and the current address is told, with a way to report it. With MFA on, Auth CS sends the current address a notification-only email; without MFA, the current address must confirm too.
Flawed: the change takes effect at once, or the current address hears nothing.
Evidence: both emails and the account state before and after confirming.
Basis: Auth CS, Changing A User's Registered Email Address; ASVS 6.3.7 (L3: notify users after updates to authentication details such as a change of email address); SP 800-63B-4 4.6 (a notification SHALL give clear instructions, including contact information, in case the recipient repudiates the event).
E3 Same answer whether the new address is taken
Send: signed in as B, with the current password, change to A's address, then to a free address.
Safe: the same answer for both.
Flawed: "That address is already in use", which turns the form into a way to check who has an account.
Evidence: both responses, side by side.
Basis: no source names this flow; it is the discrepancy Auth CS describes for login, recovery and registration, inside the account.
E4 A pending change does not move reset emails
Send: after E2, before confirming, request a reset for B's current address and for the pending new address.
Safe: the reset goes only to the confirmed, current address.
Flawed: the pending address receives a reset link, which completes the takeover API2:2023 describes without any confirmation.
Evidence: both responses and both inboxes.
Basis: no source names this check; API2:2023's second example scenario is the chain it guards against; CWE-640 (never let the user control what email address the reset goes to).
FLOW 5: REAUTHENTICATION BEFORE A SENSITIVE ACTION
A1 A password change asks for the current password
Send: signed in as B, change the password with no current password, then with a wrong one.
Safe: both refused.
Flawed: the password changes. WSTG-ATHN-09 calls a change without the current password the most insecure scenario, because anyone who takes control of a valid session could change it.
Evidence: both responses.
Basis: ASVS 6.2.3 (L1); Auth CS, Change Password Feature; WSTG-ATHN-09; CWE-620.
A2 Recovery details and second-factor settings need full reauthentication
Send: signed in as B, change a recovery phone number, add or remove a second factor, or change any other detail used in account recovery.
Safe: full reauthentication first.
Flawed: the change goes through on the session alone.
Evidence: each response.
Basis: ASVS 7.5.1 (L2); API2:2023 (require re-authentication for sensitive operations such as changing the account owner email address or 2FA phone number).
A3 Highly sensitive actions ask again
Send: signed in as B, the action your application treats as highly sensitive, such as sending an order to a new delivery address or changing payout details.
Safe: further authentication with at least one factor, or secondary verification.
Flawed: the session alone is enough.
Evidence: the response.
Basis: ASVS 7.5.3 (L3); Auth CS (gives shipping a purchase to a new address as an example).
A4 Reauthentication asks for something the account already has
Send: look at what the reauthentication prompt accepts.
Safe: the current password, a passkey or another factor already bound to the account.
Flawed: a secret question in place of a bound factor.
Evidence: a screenshot of the prompt.
Basis: Auth CS, Re-authentication Mechanisms (an authenticator already bound to the account; do not substitute security questions).
A5 A successful reauthentication starts a new session token
Send: reauthenticate as B and compare the session cookie before and after.
Safe: a new token, and the old one no longer works.
Flawed: the same token before and after.
Evidence: both Set-Cookie values, redacted.
Basis: ASVS 7.2.4 (L1). Session rotation is covered in the session management guide.
AFTER THE RUN: THE LOG
X1 Read the log for everything above
Safe: every sign-in attempt, successful or not, with metadata such as when, where, who and what; reset requests and completions; email and password change requests; refused reauthentication. No password anywhere, including a password typed into the email field.
Flawed: failures missing, or a password or live reset token in clear text.
Evidence: the log lines for the run, with any secret redacted before you store them.
Basis: ASVS 16.3.1 (L2: all authentication operations logged, successful and unsuccessful); ASVS 16.2.1 (L2: necessary metadata such as when, where, who and what); ASVS 16.2.5 (L2: logging by protection level, for example credentials may not be allowed in logs and session tokens only hashed or masked); Auth CS (log and review all failures, password failures and lockouts); CWE-204 (passwords should never be saved to log files).
================================================================
PART 2: THE LAB FILES
================================================================
Make an empty folder, save the five files below into it with the names shown, and open a terminal in that folder. The server runs in two versions. The flawed version gives itself away through different wording, a different status or redirect, and a timing gap, because it hashes a password only when the account exists and waits for the email provider before replying. The fixed version gives one reply per flow, does comparable work for an address with an account and one without, queues email, and asks for the current password before an email or password change.
================================================================
FILE 1 OF 5: auth-lab-server.mjs
================================================================
// auth-lab-server.mjs: a small sign-in service with invented accounts, in a
// flawed version and a fixed version. Illustration only. It listens on
// 127.0.0.1 on a port the system picks, keeps everything in memory and sends
// no real email: every message lands in an in-memory outbox.
import { createServer } from 'node:http'
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
// One of the scrypt settings in the OWASP Password Storage Cheat Sheet:
// N=2^14 (16 MiB), r=8, p=5. It fits inside Node's default maxmem.
const SCRYPT_SETTINGS = { N: 16384, r: 8, p: 5 }
const HASH_BYTES = 32
// Stands in for the time an email provider takes to accept a message.
const MAIL_PROVIDER_DELAY_MS = 30
// An example lifetime for a reset link. Choose your own.
const RESET_LINK_LIFETIME_MS = 20 * 60 * 1000
const MAX_BODY_BYTES = 10000
// Invented accounts on example.com, a domain reserved for examples.
export const LAB_ACCOUNTS = [
{ email: 'sam@example.com', password: 'sam-lab-password-one' },
{ email: 'alex@example.com', password: 'alex-lab-password-two' },
]
const GENERIC_SIGN_IN_FAILURE = 'Email address or password is incorrect.'
const GENERIC_RESET_REPLY = 'If that email address has an account, we have sent it a link to reset the password.'
const GENERIC_SIGN_UP_REPLY = 'Check your inbox: we have sent that address a message to finish signing up.'
const GENERIC_EMAIL_CHANGE_REPLY = 'Check the new address for a link to confirm the change. We have also told your current address.'
// version is 'flawed' or 'fixed'.
export async function startAuthLab(version) {
if (version !== 'flawed' && version !== 'fixed') throw new Error('version must be flawed or fixed')
const lab = await createLabState(version)
const handlers = version === 'fixed' ? fixedHandlers : flawedHandlers
const server = createServer(function (request, response) {
routeRequest(lab, handlers, request, response).catch(function () {
sendJson(response, 400, { message: 'The request could not be read.' })
})
})
await new Promise(function (resolve) { server.listen(0, '127.0.0.1', resolve) })
lab.server = server
lab.port = server.address().port
return lab
}
export function stopAuthLab(lab) {
lab.server.closeAllConnections()
return new Promise(function (resolve) { lab.server.close(resolve) })
}
// Waits for every queued email to reach the outbox.
export async function flushMail(lab) {
await Promise.all(lab.pendingMail)
}
async function createLabState(version) {
const lab = {
version: version, accounts: new Map(), sessions: new Map(), resetLinks: new Map(),
pendingEmailChanges: new Map(), outbox: [], pendingMail: [], events: [], hashCalls: 0,
}
for (const account of LAB_ACCOUNTS) {
lab.accounts.set(account.email, await buildAccount(lab, account.email, account.password))
}
// The fixed version checks unknown addresses against this account, so they cost the same work.
lab.dummyAccount = await buildAccount(lab, 'no-account', randomBytes(16).toString('hex'))
lab.dummyAccount.active = false
lab.hashCalls = 0
return lab
}
async function routeRequest(lab, handlers, request, response) {
const path = new URL(request.url, 'http://127.0.0.1').pathname
const handler = Object.hasOwn(handlers, path) ? handlers[path] : null
if (!handler) return sendJson(response, 404, { message: 'Not found.' })
if (request.method !== 'POST') return sendJson(response, 405, { message: 'Use POST.' })
const fields = await readJson(request)
return handler(lab, fields, request, response)
}
// ---------------------------------------------------------------------------
// The flawed version. Each handler gives away whether an address has an
// account, or lets a signed-in session change what protects the account.
// ---------------------------------------------------------------------------
const flawedHandlers = {
'/sign-up': async function (lab, fields, request, response) {
const email = normaliseEmail(fields.email)
if (lab.accounts.has(email)) {
return sendJson(response, 409, { message: 'An account with this email address already exists. Sign in instead.' })
}
lab.accounts.set(email, await buildAccount(lab, email, fields.password))
return startSession(lab, response, lab.accounts.get(email), 201, 'Welcome! Your account is ready.')
},
'/sign-in': async function (lab, fields, request, response) {
const account = lab.accounts.get(normaliseEmail(fields.email))
// Quick exit: an unknown address skips the slow hash and is sent to sign-up.
if (!account) {
const location = '/sign-up?email=' + encodeURIComponent(String(fields.email || ''))
return sendJson(response, 302, { message: 'No account uses that email address. Create one?' }, { Location: location })
}
if (!(await passwordMatches(lab, account, fields.password))) {
return sendJson(response, 401, { message: 'Incorrect password for this account.' })
}
return startSession(lab, response, account, 200, 'Signed in.')
},
'/password-reset': async function (lab, fields, request, response) {
const account = lab.accounts.get(normaliseEmail(fields.email))
if (!account) return sendJson(response, 404, { message: 'We could not find an account with that email address.' })
const token = issueResetLink(lab, account)
// Waits for the email provider before answering, so only a known address pays that delay.
await deliverMail(lab, { to: account.email, subject: 'Reset your password', token: token })
return sendJson(response, 200, { message: 'Reset link sent to ' + maskEmail(account.email) + '.' })
},
'/password-reset/confirm': async function (lab, fields, request, response) {
// The link is never marked as used and never expires, and a reset signs the user straight in.
const link = lab.resetLinks.get(hashToken(fields.token))
if (!link) return sendJson(response, 400, { message: 'This reset link is not valid.' })
await setPassword(lab, link.account, fields.new_password)
return startSession(lab, response, link.account, 200, 'Password changed. You are signed in.')
},
'/account/email': async function (lab, fields, request, response) {
const account = findSessionAccount(lab, request)
if (!account) return sendJson(response, 401, { message: 'Sign in first.' })
const newEmail = normaliseEmail(fields.new_email)
if (lab.accounts.has(newEmail)) {
return sendJson(response, 409, { message: 'That email address is already used by another account.' })
}
// No current password, no confirmation from the new address, no notice to the old one.
moveAccount(lab, account, newEmail)
return sendJson(response, 200, { message: 'Email address updated.' })
},
'/account/password': async function (lab, fields, request, response) {
const account = findSessionAccount(lab, request)
if (!account) return sendJson(response, 401, { message: 'Sign in first.' })
// No current password: whoever holds the session can lock the owner out.
await setPassword(lab, account, fields.new_password)
return sendJson(response, 200, { message: 'Password changed.' })
},
}
// ---------------------------------------------------------------------------
// The fixed version. Each flow gives the same answer for a known and an
// unknown address, does comparable work for both, queues email instead of
// waiting for it, and asks for the current password before a sensitive change.
// ---------------------------------------------------------------------------
const fixedHandlers = {
'/sign-up': async function (lab, fields, request, response) {
const email = normaliseEmail(fields.email)
// Hash on both paths, so an existing address does not answer faster.
const newAccount = await buildAccount(lab, email, fields.password)
if (lab.accounts.has(email)) {
queueMail(lab, { to: email, subject: 'Someone tried to sign up with this address. If it was you, sign in or reset your password.' })
} else {
// The account stays inactive until the address is confirmed. Confirmation is left out of this illustration.
newAccount.active = false
lab.accounts.set(email, newAccount)
queueMail(lab, { to: email, subject: 'Confirm this address to finish signing up' })
}
recordEvent(lab, 'sign-up requested', email)
return sendJson(response, 202, { message: GENERIC_SIGN_UP_REPLY })
},
'/sign-in': async function (lab, fields, request, response) {
const account = lab.accounts.get(normaliseEmail(fields.email))
// An unknown address is checked against the dummy account, so both paths run the hash once.
const passwordIsRight = await passwordMatches(lab, account || lab.dummyAccount, fields.password)
if (!account || !account.active || !passwordIsRight) {
recordEvent(lab, 'sign-in failed', fields.email)
return sendJson(response, 401, { message: GENERIC_SIGN_IN_FAILURE })
}
recordEvent(lab, 'sign-in succeeded', account.email)
return startSession(lab, response, account, 200, 'Signed in.')
},
'/password-reset': async function (lab, fields, request, response) {
const account = lab.accounts.get(normaliseEmail(fields.email))
if (account && account.active) {
// Queued, not awaited: the reply goes out before the email provider is called.
queueMail(lab, { to: account.email, subject: 'Reset your password', token: issueResetLink(lab, account) })
}
recordEvent(lab, 'password reset requested', fields.email)
return sendJson(response, 202, { message: GENERIC_RESET_REPLY })
},
'/password-reset/confirm': async function (lab, fields, request, response) {
const link = useResetLink(lab, fields.token)
if (!link) return sendJson(response, 400, { message: 'This reset link is invalid or has expired. Request a new one.' })
await setPassword(lab, link.account, fields.new_password)
queueMail(lab, { to: link.account.email, subject: 'Your password was changed. If this was not you, contact us.' })
recordEvent(lab, 'password reset completed', link.account.email)
// No automatic sign-in: the user signs in with the new password.
return sendJson(response, 200, { message: 'Password changed. Sign in with your new password.' })
},
'/account/email': async function (lab, fields, request, response) {
const account = findSessionAccount(lab, request)
if (!account) return sendJson(response, 401, { message: 'Sign in first.' })
if (!(await passwordMatches(lab, account, fields.current_password))) {
recordEvent(lab, 'email change refused: current password wrong', account.email)
return sendJson(response, 403, { message: 'Enter your current password to change your email address.' })
}
const newEmail = normaliseEmail(fields.new_email)
if (lab.accounts.has(newEmail)) {
queueMail(lab, { to: newEmail, subject: 'Someone asked to move another account to this address. Nothing has changed.' })
} else {
const token = randomBytes(32).toString('base64url')
lab.pendingEmailChanges.set(hashToken(token), { account: account, newEmail: newEmail })
queueMail(lab, { to: newEmail, subject: 'Confirm your new email address', token: token })
}
queueMail(lab, { to: account.email, subject: 'A change to your email address was requested. If this was not you, contact us.' })
recordEvent(lab, 'email change requested', account.email)
return sendJson(response, 202, { message: GENERIC_EMAIL_CHANGE_REPLY })
},
'/account/password': async function (lab, fields, request, response) {
const account = findSessionAccount(lab, request)
if (!account) return sendJson(response, 401, { message: 'Sign in first.' })
if (!(await passwordMatches(lab, account, fields.current_password))) {
recordEvent(lab, 'password change refused: current password wrong', account.email)
return sendJson(response, 403, { message: 'Enter your current password to choose a new one.' })
}
await setPassword(lab, account, fields.new_password)
queueMail(lab, { to: account.email, subject: 'Your password was changed. If this was not you, contact us.' })
recordEvent(lab, 'password changed', account.email)
return sendJson(response, 200, { message: 'Password changed.' })
},
}
// ---------------------------------------------------------------------------
// Passwords, tokens, sessions and mail.
// ---------------------------------------------------------------------------
function hashPassword(lab, password, salt) {
lab.hashCalls += 1
return new Promise(function (resolve, reject) {
scrypt(String(password || ''), salt, HASH_BYTES, SCRYPT_SETTINGS, function (error, derivedKey) {
if (error) reject(error)
else resolve(derivedKey)
})
})
}
async function buildAccount(lab, email, password) {
const salt = randomBytes(16)
return { email: email, salt: salt, hash: await hashPassword(lab, password, salt), active: true }
}
async function setPassword(lab, account, password) {
account.salt = randomBytes(16)
account.hash = await hashPassword(lab, password, account.salt)
}
async function passwordMatches(lab, account, password) {
const candidate = await hashPassword(lab, password, account.salt)
return timingSafeEqual(candidate, account.hash)
}
// Reset tokens are random, tied to one account, and stored only as a hash.
function issueResetLink(lab, account) {
const token = randomBytes(32).toString('base64url')
lab.resetLinks.set(hashToken(token), { account: account, expiresAt: Date.now() + RESET_LINK_LIFETIME_MS })
return token
}
// Single use: the link is removed the first time it is presented.
function useResetLink(lab, token) {
const key = hashToken(token)
const link = lab.resetLinks.get(key)
lab.resetLinks.delete(key)
if (!link || Date.now() > link.expiresAt) return null
return link
}
function hashToken(token) {
return createHash('sha256').update(String(token || '')).digest('hex')
}
function startSession(lab, response, account, status, message) {
const sessionId = randomBytes(32).toString('base64url')
lab.sessions.set(sessionId, account)
const cookie = 'sid=' + sessionId + '; Path=/; HttpOnly; SameSite=Lax'
return sendJson(response, status, { message: message }, { 'Set-Cookie': cookie })
}
function findSessionAccount(lab, request) {
const pairs = String(request.headers.cookie || '').split('; ')
for (const pair of pairs) {
if (pair.startsWith('sid=')) return lab.sessions.get(pair.slice(4)) || null
}
return null
}
function moveAccount(lab, account, newEmail) {
lab.accounts.delete(account.email)
account.email = newEmail
lab.accounts.set(newEmail, account)
}
function deliverMail(lab, message) {
return new Promise(function (resolve) {
setTimeout(function () {
lab.outbox.push(message)
resolve()
}, MAIL_PROVIDER_DELAY_MS)
})
}
function queueMail(lab, message) {
lab.pendingMail.push(deliverMail(lab, message))
}
// What happened, to whom and when. The password is never part of an event.
function recordEvent(lab, event, email) {
lab.events.push({ at: new Date().toISOString(), event: event, email: normaliseEmail(email) })
}
// ---------------------------------------------------------------------------
// Small helpers.
// ---------------------------------------------------------------------------
function normaliseEmail(email) {
return String(email || '').trim().toLowerCase()
}
function maskEmail(email) {
const parts = email.split('@')
return parts[0].slice(0, 1) + '***@' + parts[1]
}
function readJson(request) {
return new Promise(function (resolve, reject) {
const chunks = []
let size = 0
request.on('data', function (chunk) {
size += chunk.length
if (size > MAX_BODY_BYTES) reject(new Error('body too large'))
else chunks.push(chunk)
})
request.on('end', function () {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'))
} catch (error) {
reject(error)
}
})
})
}
function sendJson(response, status, body, extraHeaders) {
const headers = Object.assign({ 'Content-Type': 'application/json' }, extraHeaders || {})
response.writeHead(status, headers)
response.end(JSON.stringify(body))
}
================================================================
FILE 2 OF 5: lab-client.mjs
================================================================
// lab-client.mjs: sends JSON requests to the lab server on 127.0.0.1 and
// returns what came back. Shared by the other three scripts.
import { Agent, request as httpRequest } from 'node:http'
// One kept-alive connection, so connection setup is not part of each timing.
const agent = new Agent({ keepAlive: true, maxSockets: 1 })
export function postJson(lab, path, fields, cookie) {
const body = JSON.stringify(fields)
const headers = { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }
if (cookie) headers.Cookie = cookie
const options = { host: '127.0.0.1', port: lab.port, method: 'POST', path: path, headers: headers, agent: agent }
return new Promise(function (resolve, reject) {
const outgoing = httpRequest(options, function (response) {
const chunks = []
response.on('data', function (chunk) { chunks.push(chunk) })
response.on('end', function () {
resolve({
status: response.statusCode,
location: response.headers.location || '',
setCookie: (response.headers['set-cookie'] || []).join('; '),
body: JSON.parse(Buffer.concat(chunks).toString('utf8')),
})
})
})
outgoing.on('error', reject)
outgoing.end(body)
})
}
// The parts of a response that can give an account away, in one comparable object.
export function describeAnswer(answer) {
return {
status: answer.status,
location: answer.location,
setsCookie: answer.setCookie !== '',
message: answer.body.message,
}
}
export async function signIn(lab, email, password) {
const answer = await postJson(lab, '/sign-in', { email: email, password: password })
return answer.setCookie.split(';')[0]
}
export function closeClient() {
agent.destroy()
}
================================================================
FILE 3 OF 5: show-responses.mjs
================================================================
// show-responses.mjs: sends each flow's pair of requests to the flawed and
// the fixed version and prints what an outsider can see in each answer:
// status, Location header, whether a session cookie was set, the message,
// and how many times the server ran the password hash.
// Run: node show-responses.mjs
import { LAB_ACCOUNTS, flushMail, startAuthLab, stopAuthLab } from './auth-lab-server.mjs'
import { closeClient, describeAnswer, postJson, signIn } from './lab-client.mjs'
const SAM = LAB_ACCOUNTS[0]
const ALEX = LAB_ACCOUNTS[1]
const NOBODY = 'nobody@example.com'
async function sendAndDescribe(lab, label, path, fields, cookie) {
const hashCallsBefore = lab.hashCalls
const answer = await postJson(lab, path, fields, cookie)
const summary = describeAnswer(answer)
const parts = [String(summary.status)]
if (summary.location) parts.push('Location: ' + summary.location)
parts.push(summary.setsCookie ? 'session cookie set' : 'no cookie')
parts.push('hash ran ' + (lab.hashCalls - hashCallsBefore) + 'x')
console.log(' ' + (label + ' ').padEnd(40, '.') + ' ' + parts.join(' | '))
console.log(' "' + summary.message + '"')
return answer
}
async function showSignUp(lab) {
console.log(' 1. Registration')
await sendAndDescribe(lab, 'existing address (sam)', '/sign-up', { email: SAM.email, password: 'a-new-lab-password-1' })
await sendAndDescribe(lab, 'new address', '/sign-up', { email: 'new-person@example.com', password: 'a-new-lab-password-1' })
}
async function showSignIn(lab) {
console.log(' 2. Login')
await sendAndDescribe(lab, 'known address, wrong password', '/sign-in', { email: SAM.email, password: 'wrong-password-here' })
await sendAndDescribe(lab, 'unknown address', '/sign-in', { email: NOBODY, password: 'wrong-password-here' })
}
async function showPasswordReset(lab) {
console.log(' 3. Password recovery')
await sendAndDescribe(lab, 'registered address (sam)', '/password-reset', { email: SAM.email })
await sendAndDescribe(lab, 'unregistered address', '/password-reset', { email: NOBODY })
await flushMail(lab)
const resetEmail = lab.outbox.find(function (message) { return message.token && message.to === SAM.email })
const fields = { token: resetEmail.token, new_password: 'sam-lab-password-new' }
await sendAndDescribe(lab, 'reset link, first use', '/password-reset/confirm', fields)
await sendAndDescribe(lab, 'same reset link, second use', '/password-reset/confirm', fields)
}
async function showEmailChange(lab) {
console.log(' 4. Email change (signed in as alex)')
const cookie = await signIn(lab, ALEX.email, ALEX.password)
await flushMail(lab)
const before = lab.outbox.length
await sendAndDescribe(lab, 'no current password', '/account/email', { new_email: 'alex.new@example.com' }, cookie)
await sendAndDescribe(lab, 'current password, address taken', '/account/email', { new_email: SAM.email, current_password: ALEX.password }, cookie)
await sendAndDescribe(lab, 'current password, address free', '/account/email', { new_email: 'alex.other@example.com', current_password: ALEX.password }, cookie)
await flushMail(lab)
const sent = lab.outbox.slice(before)
console.log(' emails sent by these three requests: ' + (sent.length ? sent.length : 'none'))
for (const message of sent) console.log(' to ' + message.to + ': ' + message.subject)
}
async function showReauthentication(lab) {
console.log(' 5. Reauthentication before a password change (signed in as alex)')
const account = lab.accounts.get(ALEX.email) ? ALEX.email : 'alex.other@example.com'
const cookie = await signIn(lab, account, ALEX.password)
await sendAndDescribe(lab, 'no current password', '/account/password', { new_password: 'alex-lab-password-new' }, cookie)
}
async function showVersion(version) {
const lab = await startAuthLab(version)
console.log(version.toUpperCase() + ' VERSION')
await showSignUp(lab)
await showSignIn(lab)
await showPasswordReset(lab)
await showEmailChange(lab)
await showReauthentication(lab)
await flushMail(lab)
await stopAuthLab(lab)
console.log('')
}
await showVersion('flawed')
await showVersion('fixed')
closeClient()
================================================================
FILE 4 OF 5: measure-timing.mjs
================================================================
// measure-timing.mjs: times repeated requests for a known and an unknown
// address against the flawed and the fixed version, and prints the median
// and spread of each in milliseconds. Only the lab's own server on 127.0.0.1
// is measured. Your numbers will differ by machine and from run to run.
// Run: node measure-timing.mjs
import { LAB_ACCOUNTS, startAuthLab, stopAuthLab } from './auth-lab-server.mjs'
import { closeClient, postJson } from './lab-client.mjs'
const WARM_UP_ROUNDS = 3
const MEASURED_ROUNDS = 25
const KNOWN = LAB_ACCOUNTS[0].email
const UNKNOWN = 'nobody@example.com'
// Each flow builds the request for the known and the unknown case. Sign-up
// needs a fresh address every round, so its unknown case counts up.
const flows = [
{
name: 'Login',
path: '/sign-in',
known: function () { return { email: KNOWN, password: 'wrong-password-here' } },
unknown: function () { return { email: UNKNOWN, password: 'wrong-password-here' } },
},
{
name: 'Password recovery',
path: '/password-reset',
known: function () { return { email: KNOWN } },
unknown: function () { return { email: UNKNOWN } },
},
{
name: 'Registration',
path: '/sign-up',
known: function () { return { email: KNOWN, password: 'a-new-lab-password-1' } },
unknown: function (round) { return { email: 'new-' + round + '@example.com', password: 'a-new-lab-password-1' } },
},
]
async function timeRequest(lab, path, fields) {
const startedAt = performance.now()
await postJson(lab, path, fields)
return performance.now() - startedAt
}
// Alternates which case goes first in each round, so drift affects both equally.
async function measureFlow(lab, flow) {
const samples = { known: [], unknown: [] }
for (let round = 0; round < WARM_UP_ROUNDS + MEASURED_ROUNDS; round++) {
const order = round % 2 === 0 ? ['known', 'unknown'] : ['unknown', 'known']
for (const which of order) {
const elapsed = await timeRequest(lab, flow.path, flow[which](round))
if (round >= WARM_UP_ROUNDS) samples[which].push(elapsed)
}
}
return samples
}
function percentile(sortedValues, fraction) {
const position = (sortedValues.length - 1) * fraction
const lower = Math.floor(position)
const upper = Math.ceil(position)
return sortedValues[lower] + (sortedValues[upper] - sortedValues[lower]) * (position - lower)
}
function summarise(values) {
const sorted = values.slice().sort(function (a, b) { return a - b })
return {
median: percentile(sorted, 0.5),
lowerQuartile: percentile(sorted, 0.25),
upperQuartile: percentile(sorted, 0.75),
min: sorted[0],
max: sorted[sorted.length - 1],
}
}
function formatMs(value) {
return value.toFixed(1).padStart(6)
}
function printRow(label, stats) {
console.log(
' ' + label.padEnd(16) +
'median ' + formatMs(stats.median) +
' middle half ' + formatMs(stats.lowerQuartile) + ' to ' + formatMs(stats.upperQuartile) +
' range ' + formatMs(stats.min) + ' to ' + formatMs(stats.max)
)
}
async function measureVersion(version) {
const lab = await startAuthLab(version)
console.log(version.toUpperCase() + ' VERSION')
for (const flow of flows) {
const samples = await measureFlow(lab, flow)
const known = summarise(samples.known)
const unknown = summarise(samples.unknown)
console.log(' ' + flow.name)
printRow('has an account', known)
printRow('no account', unknown)
console.log(' median difference, has an account minus no account: ' + (known.median - unknown.median).toFixed(1) + ' ms')
}
await stopAuthLab(lab)
console.log('')
}
console.log('Node.js ' + process.version + ' on ' + process.platform + ' ' + process.arch)
console.log('Times in milliseconds for ' + MEASURED_ROUNDS + ' requests per row, after ' + WARM_UP_ROUNDS + ' warm-up rounds.')
console.log('Every request carries a wrong password or no password, so none of them signs in.')
console.log('')
await measureVersion('flawed')
await measureVersion('fixed')
closeClient()
================================================================
FILE 5 OF 5: auth-flows.test.mjs
================================================================
// auth-flows.test.mjs: regression tests for the five flows. They assert on
// things that stay the same from one machine and one run to the next:
// messages, status codes, headers, how many times the password hash runs,
// what reaches the outbox and what reaches the event log. No test asserts
// a number of milliseconds.
// Run: node auth-flows.test.mjs (fixed version: every test passes)
// node auth-flows.test.mjs flawed (flawed version: all but the baseline fail)
import assert from 'node:assert/strict'
import { afterEach, beforeEach, test } from 'node:test'
import { LAB_ACCOUNTS, flushMail, startAuthLab, stopAuthLab } from './auth-lab-server.mjs'
import { closeClient, describeAnswer, postJson, signIn } from './lab-client.mjs'
const version = process.argv[2] || 'fixed'
const SAM = LAB_ACCOUNTS[0]
const ALEX = LAB_ACCOUNTS[1]
const NOBODY = 'nobody@example.com'
let lab
// Each test gets a fresh lab, so no test depends on another.
beforeEach(async function () { lab = await startAuthLab(version) })
afterEach(async function () { await flushMail(lab); await stopAuthLab(lab) })
process.on('exit', closeClient)
async function countHashCalls(path, fields) {
const before = lab.hashCalls
await postJson(lab, path, fields)
return lab.hashCalls - before
}
test('baseline: the right password signs in', async function () {
const answer = await postJson(lab, '/sign-in', { email: SAM.email, password: SAM.password })
assert.equal(answer.status, 200)
assert.notEqual(answer.setCookie, '')
})
test('login: a wrong password and an unknown address get the same answer', async function () {
const known = await postJson(lab, '/sign-in', { email: SAM.email, password: 'wrong-password-here' })
const unknown = await postJson(lab, '/sign-in', { email: NOBODY, password: 'wrong-password-here' })
assert.deepEqual(describeAnswer(unknown), describeAnswer(known))
})
test('login: the password hash runs once for a known and once for an unknown address', async function () {
assert.equal(await countHashCalls('/sign-in', { email: SAM.email, password: 'wrong-password-here' }), 1)
assert.equal(await countHashCalls('/sign-in', { email: NOBODY, password: 'wrong-password-here' }), 1)
})
test('login: a failed attempt is logged, without the password', async function () {
await postJson(lab, '/sign-in', { email: NOBODY, password: 'typed-by-mistake' })
const failures = lab.events.filter(function (entry) { return entry.event === 'sign-in failed' })
assert.equal(failures.length, 1)
assert.equal(failures[0].email, NOBODY)
assert.ok(!JSON.stringify(lab.events).includes('typed-by-mistake'))
})
test('recovery: a registered and an unregistered address get the same answer', async function () {
const known = await postJson(lab, '/password-reset', { email: SAM.email })
const unknown = await postJson(lab, '/password-reset', { email: NOBODY })
assert.deepEqual(describeAnswer(unknown), describeAnswer(known))
})
test('recovery: a reset link works once and does not sign the user in', async function () {
await postJson(lab, '/password-reset', { email: SAM.email })
await flushMail(lab)
const resetEmail = lab.outbox.find(function (message) { return message.token && message.to === SAM.email })
const fields = { token: resetEmail.token, new_password: 'sam-lab-password-new' }
const firstUse = await postJson(lab, '/password-reset/confirm', fields)
const secondUse = await postJson(lab, '/password-reset/confirm', fields)
assert.equal(firstUse.status, 200)
assert.equal(firstUse.setCookie, '')
assert.equal(secondUse.status, 400)
})
test('registration: an existing and a new address get the same answer, with no session', async function () {
const existing = await postJson(lab, '/sign-up', { email: SAM.email, password: 'a-new-lab-password-1' })
const fresh = await postJson(lab, '/sign-up', { email: 'new-person@example.com', password: 'a-new-lab-password-1' })
assert.deepEqual(describeAnswer(fresh), describeAnswer(existing))
assert.equal(existing.setCookie, '')
})
test('registration: the password hash runs for an existing and for a new address', async function () {
assert.equal(await countHashCalls('/sign-up', { email: SAM.email, password: 'a-new-lab-password-1' }), 1)
assert.equal(await countHashCalls('/sign-up', { email: 'new-person@example.com', password: 'a-new-lab-password-1' }), 1)
})
test('email change: refused without the current password', async function () {
const cookie = await signIn(lab, ALEX.email, ALEX.password)
const answer = await postJson(lab, '/account/email', { new_email: 'alex.new@example.com' }, cookie)
assert.equal(answer.status, 403)
assert.ok(lab.accounts.has(ALEX.email))
})
test('email change: the answer is the same whether the new address is taken or free', async function () {
const cookie = await signIn(lab, ALEX.email, ALEX.password)
const taken = await postJson(lab, '/account/email', { new_email: SAM.email, current_password: ALEX.password }, cookie)
const free = await postJson(lab, '/account/email', { new_email: 'alex.new@example.com', current_password: ALEX.password }, cookie)
assert.deepEqual(describeAnswer(free), describeAnswer(taken))
})
test('email change: the current address is told about the request', async function () {
const cookie = await signIn(lab, ALEX.email, ALEX.password)
await postJson(lab, '/account/email', { new_email: 'alex.new@example.com', current_password: ALEX.password }, cookie)
await flushMail(lab)
assert.ok(lab.outbox.some(function (message) { return message.to === ALEX.email }))
})
test('reauthentication: a password change is refused without the current password', async function () {
const cookie = await signIn(lab, ALEX.email, ALEX.password)
const answer = await postJson(lab, '/account/password', { new_password: 'alex-lab-password-new' }, cookie)
assert.equal(answer.status, 403)
})
================================================================
PART 3: WHAT EACH FLOW TELLS AN OUTSIDER
================================================================
Command: node show-responses.mjs
FLAWED VERSION
1. Registration
existing address (sam) ................. 409 | no cookie | hash ran 0x
"An account with this email address already exists. Sign in instead."
new address ............................ 201 | session cookie set | hash ran 1x
"Welcome! Your account is ready."
2. Login
known address, wrong password .......... 401 | no cookie | hash ran 1x
"Incorrect password for this account."
unknown address ........................ 302 | Location: /sign-up?email=nobody%40example.com | no cookie | hash ran 0x
"No account uses that email address. Create one?"
3. Password recovery
registered address (sam) ............... 200 | no cookie | hash ran 0x
"Reset link sent to s***@example.com."
unregistered address ................... 404 | no cookie | hash ran 0x
"We could not find an account with that email address."
reset link, first use .................. 200 | session cookie set | hash ran 1x
"Password changed. You are signed in."
same reset link, second use ............ 200 | session cookie set | hash ran 1x
"Password changed. You are signed in."
4. Email change (signed in as alex)
no current password .................... 200 | no cookie | hash ran 0x
"Email address updated."
current password, address taken ........ 409 | no cookie | hash ran 0x
"That email address is already used by another account."
current password, address free ......... 200 | no cookie | hash ran 0x
"Email address updated."
emails sent by these three requests: none
5. Reauthentication before a password change (signed in as alex)
no current password .................... 200 | no cookie | hash ran 1x
"Password changed."
FIXED VERSION
1. Registration
existing address (sam) ................. 202 | no cookie | hash ran 1x
"Check your inbox: we have sent that address a message to finish signing up."
new address ............................ 202 | no cookie | hash ran 1x
"Check your inbox: we have sent that address a message to finish signing up."
2. Login
known address, wrong password .......... 401 | no cookie | hash ran 1x
"Email address or password is incorrect."
unknown address ........................ 401 | no cookie | hash ran 1x
"Email address or password is incorrect."
3. Password recovery
registered address (sam) ............... 202 | no cookie | hash ran 0x
"If that email address has an account, we have sent it a link to reset the password."
unregistered address ................... 202 | no cookie | hash ran 0x
"If that email address has an account, we have sent it a link to reset the password."
reset link, first use .................. 200 | no cookie | hash ran 1x
"Password changed. Sign in with your new password."
same reset link, second use ............ 400 | no cookie | hash ran 0x
"This reset link is invalid or has expired. Request a new one."
4. Email change (signed in as alex)
no current password .................... 403 | no cookie | hash ran 1x
"Enter your current password to change your email address."
current password, address taken ........ 202 | no cookie | hash ran 1x
"Check the new address for a link to confirm the change. We have also told your current address."
current password, address free ......... 202 | no cookie | hash ran 1x
"Check the new address for a link to confirm the change. We have also told your current address."
emails sent by these three requests: 4
to sam@example.com: Someone asked to move another account to this address. Nothing has changed.
to alex@example.com: A change to your email address was requested. If this was not you, contact us.
to alex.other@example.com: Confirm your new email address
to alex@example.com: A change to your email address was requested. If this was not you, contact us.
5. Reauthentication before a password change (signed in as alex)
no current password .................... 403 | no cookie | hash ran 1x
"Enter your current password to choose a new one."
Reading the evidence:
Flawed Every flow answers differently for the two addresses: 409 against 201 at sign-up, 401 against a 302 redirect to sign-up at login, 200 with a masked address against 404 at recovery, and 409 "already used" at email change. At login the hash ran only for the address with an account, and at sign-up only for the new address. The same reset link worked twice and signed the user in both times. The email address and the password changed without the current password, and the three email change requests sent no email at all.
Fixed Each pair gets the same status, message, Location header and cookie behaviour. The hash ran once on both sides of the sign-up and login pairs. The second use of the reset link was refused, and the reset set no session cookie. The email change and password change without the current password were refused with 403. The two email change requests with the current password sent a confirmation link to the free address, a notice to the taken address saying nothing had changed, and a notice to alex's current address each time.
================================================================
PART 4: THE TIMING GAP AND ITS REMOVAL
================================================================
Command: node measure-timing.mjs
Node.js v26.0.0 on darwin arm64
Times in milliseconds for 25 requests per row, after 3 warm-up rounds.
Every request carries a wrong password or no password, so none of them signs in.
FLAWED VERSION
Login
has an account median 124.0 middle half 121.5 to 126.3 range 117.6 to 129.8
no account median 0.2 middle half 0.2 to 0.3 range 0.1 to 0.5
median difference, has an account minus no account: 123.7 ms
Password recovery
has an account median 32.5 middle half 32.0 to 32.7 range 31.0 to 33.2
no account median 0.3 middle half 0.2 to 0.4 range 0.2 to 0.7
median difference, has an account minus no account: 32.2 ms
Registration
has an account median 0.2 middle half 0.2 to 0.3 range 0.1 to 0.4
no account median 125.1 middle half 123.1 to 127.4 range 116.6 to 131.5
median difference, has an account minus no account: -124.9 ms
FIXED VERSION
Login
has an account median 127.0 middle half 122.0 to 127.6 range 116.9 to 130.0
no account median 126.4 middle half 125.0 to 129.4 range 117.2 to 131.5
median difference, has an account minus no account: 0.6 ms
Password recovery
has an account median 0.1 middle half 0.1 to 0.1 range 0.1 to 0.2
no account median 0.1 middle half 0.1 to 0.1 range 0.1 to 0.2
median difference, has an account minus no account: 0.0 ms
Registration
has an account median 124.5 middle half 120.6 to 126.0 range 118.7 to 130.6
no account median 123.2 middle half 121.2 to 127.0 range 118.6 to 130.5
median difference, has an account minus no account: 1.3 ms
Reading the evidence:
Flawed login 124.0 ms against 0.2 ms. Only the address with an account went through scrypt, and the two ranges do not overlap, so on this machine a single request each way would have told them apart.
Flawed recovery 32.5 ms against 0.3 ms. The gap is the stand-in email provider, MAIL_PROVIDER_DELAY_MS of 30, which the flawed version waits for before it replies.
Flawed registration 0.2 ms against 125.1 ms. The gap runs the other way: a new address has its password hashed, and an existing one is turned away at once.
Fixed Login differs by 0.6 ms and registration by 1.3 ms, and each median sits inside the other case's middle half. Recovery replies in 0.1 ms either way, because the email is queued after the reply.
These figures come from one run on an Apple M3 Max machine with Node.js 26.0.0, over the loopback interface. Yours will differ by machine and from run to run, and a network adds its own jitter. The gap and its removal are the point, not the numbers.
================================================================
PART 5: THE REGRESSION TEST
================================================================
The tests assert on things that stay the same between machines and runs: messages, status codes, headers, how many times the password hash runs, what reaches the outbox and what reaches the event log. None of them asserts a number of milliseconds.
Command: node auth-flows.test.mjs
✔ baseline: the right password signs in (505.092625ms)
✔ login: a wrong password and an unknown address get the same answer (629.609041ms)
✔ login: the password hash runs once for a known and once for an unknown address (624.034166ms)
✔ login: a failed attempt is logged, without the password (505.862916ms)
✔ recovery: a registered and an unregistered address get the same answer (419.985958ms)
✔ recovery: a reset link works once and does not sign the user in (572.587125ms)
✔ registration: an existing and a new address get the same answer, with no session (647.548208ms)
✔ registration: the password hash runs for an existing and for a new address (665.356958ms)
✔ email change: refused without the current password (626.100167ms)
✔ email change: the answer is the same whether the new address is taken or free (778.525042ms)
✔ email change: the current address is told about the request (645.29375ms)
✔ reauthentication: a password change is refused without the current password (627.545792ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 7251.271417
The process exits with code 0.
Command: node auth-flows.test.mjs flawed
✔ baseline: the right password signs in (519.90925ms)
✖ login: a wrong password and an unknown address get the same answer (502.560084ms)
✖ login: the password hash runs once for a known and once for an unknown address (490.645125ms)
✖ login: a failed attempt is logged, without the password (369.504875ms)
✖ recovery: a registered and an unregistered address get the same answer (395.674ms)
✖ recovery: a reset link works once and does not sign the user in (648.648666ms)
✖ registration: an existing and a new address get the same answer, with no session (494.223542ms)
✖ registration: the password hash runs for an existing and for a new address (383.013875ms)
✖ email change: refused without the current password (493.785708ms)
✖ email change: the answer is the same whether the new address is taken or free (511.7975ms)
✖ email change: the current address is told about the request (498.120625ms)
✖ reauthentication: a password change is refused without the current password (634.970208ms)
ℹ tests 12
ℹ suites 0
ℹ pass 1
ℹ fail 11
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5946.347167
✖ failing tests:
test at auth-flows.test.mjs:36:1
✖ login: a wrong password and an unknown address get the same answer (502.560084ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
+ location: '/sign-up?email=nobody%40example.com',
+ message: 'No account uses that email address. Create one?',
- location: '',
- message: 'Incorrect password for this account.',
setsCookie: false,
+ status: 302
- status: 401
}
(stack trace and error object removed here)
test at auth-flows.test.mjs:42:1
✖ login: the password hash runs once for a known and once for an unknown address (490.645125ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
0 !== 1
(stack trace and error object removed here)
test at auth-flows.test.mjs:55:1
✖ recovery: a registered and an unregistered address get the same answer (395.674ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
location: '',
+ message: 'We could not find an account with that email address.',
- message: 'Reset link sent to s***@example.com.',
setsCookie: false,
+ status: 404
- status: 200
}
(stack trace and error object removed here)
test at auth-flows.test.mjs:73:1
✖ registration: an existing and a new address get the same answer, with no session (494.223542ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
location: '',
+ message: 'Welcome! Your account is ready.',
+ setsCookie: true,
+ status: 201
- message: 'An account with this email address already exists. Sign in instead.',
- setsCookie: false,
- status: 409
}
(stack trace and error object removed here)
test at auth-flows.test.mjs:85:1
✖ email change: refused without the current password (493.785708ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 403
(stack trace and error object removed here)
(6 more failure blocks of the same form are left out here.)
The process exits with code 1, so a pipeline step that runs the test fails.
================================================================
PART 6: POINT THE TESTS AT YOUR OWN APPLICATION
================================================================
1. Copy auth-flows.test.mjs and lab-client.mjs into your project's tests.
2. Replace startAuthLab with your application started on a test port with seeded test accounts, and change the paths and field names to your own.
3. Replace lab.hashCalls with a counter around your own password hashing function in the test build. If you cannot reach it, keep the timing row in the pack instead of those two tests.
4. Replace lab.outbox with your test mail transport and lab.events with your test log output.
5. For timing on staging, change measure-timing.mjs to send to your staging host and paths (node:https for an HTTPS address). Run it from one machine, keep the machine, network path and date with the numbers, and run it only against a system you own or are authorised in writing to test.
6. Run the tests in the pipeline that deploys the application, and only against staging or a local copy with test accounts, never against real customers' accounts.What broken authentication means
OWASP's Top 10:2025 files broken authentication under A07 Authentication Failures and gives the test in one line: the vulnerability is present when an attacker can trick a system into recognising an invalid or incorrect user as legitimate.
MITRE describes the same weakness from the code's side as CWE-287, Improper Authentication: when an actor claims an identity, the product does not prove, or insufficiently proves, that the claim is correct.
OWASP's API Security Top 10 uses the name directly: API2:2023 is Broken Authentication. It says attackers who exploit it can gain complete control of other users' accounts, read their personal data and perform sensitive actions on their behalf, while the system is unlikely to tell their actions from the real user's.
It also makes a point this guide builds on: forgot-password and reset flows should be treated the same way as authentication mechanisms.
A sign-in system is more than its login form. This guide covers the five flows that decide who gets into an account and who can take one over: registration, login, password recovery, email change, and reauthentication before a sensitive action. Account enumeration, where those flows reveal which email addresses have accounts, is the worked example.
Five neighbouring topics have their own guides. Credential stuffing covers passwords leaked from other sites being replayed on your login, and the throttling and breached-password checks that answer it. MFA security covers second factors and how they are enrolled and recovered. Rate limiting covers how many attempts each flow allows. Session management covers what happens after sign-in, and OAuth and OIDC security covers signing in through another provider.
Authentication vulnerabilities live in five flows
Each flow answers a question for someone who has not proved who they are yet, and each one can answer too much.
- Registration decides who may create an account and whether the address is theirs. Built carelessly, it confirms which addresses already have accounts, or switches on an account for an address nobody confirmed.
- Login decides whether this person holds this account's password. Built carelessly, it says which half was wrong, takes longer when the account exists, or checks only part of the password.
- Password recovery lets someone in without the password. Built carelessly, it is an easier door than login: a link that works twice, a token that can be guessed, a reset that signs the user straight in or skips the second factor.
- Email change moves the address that reset links go to. Built carelessly, it lets anyone holding a session send every future reset email to an inbox of their choosing.
- Reauthentication asks a signed-in person to prove it again before something that matters. Left out, a stolen or unattended session is enough to change the password.
Every channel that shares the accounts
The five flows exist wherever the same accounts can be used. API2:2023 asks teams to know every possible way to authenticate to the API, naming mobile, web and deep links that implement one-click authentication. OWASP's test WSTG-ATHN-10 looks for weaker alternative channels for the same accounts, such as a mobile-optimised site, a partner website, a staging copy, a mobile app or a call centre, and says they may undermine the assurance of a primary form that has no flaws of its own.
ASVS 5.0 requirement 6.3.4, at Level 2, asks that, where an application has more than one authentication pathway, none is undocumented and controls and authentication strength are enforced consistently across them.
User enumeration: the worked example
Account enumeration, also called user enumeration, is the leak where your application tells a stranger whether an email address has an account.
OWASP's test for it, WSTG-IDNT-04, has two objectives: review the processes that identify users, such as registration and login, and enumerate users where possible through response analysis. The places it looks include login error messages and error codes, URLs and redirects, page titles, messages from a password recovery facility, and response times.
MITRE catalogues the message version as CWE-204, Observable Response Discrepancy: different responses that reveal internal state to an unauthorised actor. Its own example is a login that prints one message for an unknown username and another for a wrong password, which CWE-204 says makes it easier for an attacker to obtain half of the necessary credentials.
The timing version is CWE-208, Observable Timing Discrepancy: two operations that take different amounts of time in a way someone can observe, revealing security-relevant information. Both are children of CWE-203, Observable Discrepancy.
WSTG-IDNT-04 says the list can then be used to attack the application, for example through a brute force or default username and password attack. With valid addresses in hand, every password guess lands on a real account instead of being spread across addresses that do not exist.
A confirmed list also says who your customers are. For a clinic, a lender or a support service, the fact that an address has an account can be sensitive in its own right. It also tells a phisher which people to send a fake reset email to, written to look like yours.
The OWASP Authentication Cheat Sheet calls what enumeration needs a discrepancy factor, and adds that protection against brute-force attacks helps against enumeration too, because it stops an attacker applying it at scale. The rate limiting guide covers that side.
The fix the sources give is one answer for every outcome. The Authentication Cheat Sheet says login, password reset and password recovery must respond with a generic error message whether the user ID or password was wrong, the account does not exist, or the account is locked or disabled, and that registration can take the same approach.
Its correct reply for password recovery is the conditional one: "If that email address is in our database, we will send you an email to reset your password." It lists "We just sent you a password reset link." and "This email address doesn't exist in our database." as incorrect, because each one answers the question.
The Top 10:2025 asks for the same message for all outcomes across registration, credential recovery and API pathways, and the Forgot Password Cheat Sheet's first instruction is a consistent message for existent and non-existent accounts.
The conditional sentence works because it is true either way. The system has done what it says, and the real owner still gets the email. The difference moves from the page, which anyone can read, to the inbox, which only the owner can read.
Wording is one channel among several. The cheat sheet warns that an application can show the same page and still answer 200 for one case and 403 for the other, which can leak whether the account is valid through the status code. Compare the whole response: status, headers such as Location and Set-Cookie, and body.
The Authentication Cheat Sheet shows how timing leaks with pseudo-code. In what it calls the quick exit approach, the application checks whether the user exists and returns an error at once if not, so only a real account goes on to hash the password, and the same error arrives later for a real account than for an unknown one.
Its fix runs the same process whatever the user or password, so the application returns in approximately the same time. The Forgot Password Cheat Sheet asks for responses in a consistent amount of time, which it says could be achieved through asynchronous calls or by following the same logic instead of a quick exit, and WSTG-IDNT-04 notes that a request which calls an external service, such as sending a forgotten-password email, can add several hundred milliseconds.
ASVS 5.0 requirement 6.3.8 gives all three channels as examples: valid users must not be deducible from failed authentication challenges, such as by error messages, HTTP response codes or different response times, and registration and forgot password must have the same protection. It sits at Level 3, the highest of the standard's three levels, which increase in depth and complexity.
The ASVS introduction says each level sets the requirements needed to achieve it and leaves the requirements of higher levels as recommendations. The cheat sheets and the Top 10 ask for consistent messages without tying them to a level.
A constant-time comparison does not settle it alone. The Node.js documentation says crypto.timingSafeEqual compares bytes in constant time, and warns that using it is no assurance that the surrounding code is timing-safe. In a sign-in handler the surrounding code is the account lookup and the password hash, which is why the fix is to hash for an unknown address too.
Registration: where usability and enumeration resistance pull apart
Registration is the hardest flow to make silent, because someone signing up with an address that already has an account needs to be told something.
The Authentication Cheat Sheet names the cost: a legitimate user may be confused by generic messages, find the application hard to use and leave after several retries. It says the decision to return a generic message can be based on the criticality of the application and its data.
Its correct reply for account creation is "A link to activate your account has been emailed to the address provided.", and it lists "This user ID is already in use." and "Welcome! You have signed up successfully." as incorrect.
Where a generic message cannot be returned because the user experience must be preserved, it suggests a CAPTCHA on that feature, and it notes that brute-force protection helps too, because it stops enumeration at scale.
One way to keep both is to answer every sign-up with the same "check your inbox" message and let the email carry the difference. A new address gets the link to finish signing up.
An address that already has an account gets a note saying someone tried to sign up with it, with links to sign in or reset the password. The owner of the inbox learns what they need, and a stranger at the form learns nothing.
The lab's fixed version follows this pattern. No source cited here prescribes that second email, so treat it as one design among several.
The email step does a second job. The cheat sheet says users should be permitted to use their email address as a username provided the email is verified during sign-up, and WSTG-IDNT-02, OWASP's registration test, asks whether registered identities are verified and whether the same person can register more than once. An account that works before its address is confirmed lets anyone register an address they do not own.
Password rules belong to this flow as well. ASVS 5.0 requirement 6.2.1, at Level 1, asks for at least 8 characters and strongly recommends 15. NIST SP 800-63B-4, published in July 2025 to supersede SP 800-63B and focused on authentication to government information systems, says verifiers SHALL require at least 15 characters for a password used on its own and at least 8 when it is used only as part of multi-factor authentication.
ASVS 6.2.5, at Level 1, rules out composition rules such as a required number of capitals, digits or symbols, and 6.2.9, at Level 2, asks that passwords of at least 64 characters are accepted. Checking new passwords against breached ones is covered in the credential stuffing guide.
Login security: one answer and one amount of work
The login form answers the enumeration question most directly.
The Authentication Cheat Sheet's correct reply is "Login failed; Invalid user ID or password." Its incorrect examples include "Login for User foo: invalid password.", "Login failed, invalid user ID.", "Login failed; account disabled." and "Login failed; this user is not active." The last two matter because a locked or disabled account is also a fact about who has an account, and the cheat sheet asks for the generic message there too.
Doing the same work for every attempt means hashing the submitted password even when no account matches. A plain way to do it is a dummy record, created at start-up with the same hashing function and settings as real accounts, that an unknown address is checked against.
The lab's fixed version does this, and its regression test checks the result in a way that does not depend on the machine: the password hash runs once for an address with an account and once for an address without one.
Verify the whole password. ASVS 5.0 requirement 6.2.8, at Level 1, asks that the password is verified exactly as received, without truncation or case changes, and SP 800-63B-4 says verifiers SHALL verify the entire submitted password. The Authentication Cheat Sheet says to compare the submitted password with the stored hash using a secure comparison function from the language or framework where possible, and, where that is not possible, to make sure the comparison function has a maximum input length, against denial of service with very long inputs, sets the type of both values explicitly and returns in constant time.
How many failed attempts the form allows, and how to slow guessing without locking real people out, is covered in the rate limiting and credential stuffing guides.
How the password hash should be set up
The hash is part of the login flow's design. The OWASP Password Storage Cheat Sheet, as it read when this page was reviewed on 14 November 2026, gives these minimums: Argon2id with 19 MiB of memory, an iteration count of 2 and 1 degree of parallelism, or one of the other Argon2id settings it lists as giving an equal level of defence, from 46 MiB with 1 iteration to 7 MiB with 5; where Argon2id is not available, scrypt with a CPU and memory cost parameter of 2^17, a block size of 8 and a parallelisation parameter of 1, or one of the other scrypt settings it lists as giving a similar minimal level of defence; bcrypt only in legacy systems where Argon2 and scrypt are not available, with a work factor of 10 or more and a password limit of 72 bytes; and, where FIPS-140 compliance is required, PBKDF2 with 600,000 or more iterations of HMAC-SHA-256.
These numbers change as hardware does, so read the cheat sheet itself before you choose.
The lab uses one of its scrypt rows, N=2^14 with r=8 and p=5, which fits inside the memory limit Node.js applies to scrypt by default.
SP 800-63B-4 sets the same direction in its own terms: verifiers SHALL store passwords in a form that resists offline attacks, salted and hashed with a suitable password hashing scheme, with a salt of at least 32 bits, and the cost factor SHOULD be as high as practical without hurting verifier performance.
ASVS 5.0 requirement 11.4.2, at Level 2, asks for an approved, computationally intensive password hashing function with settings based on current guidance. The cheat sheet flags the trade-off: a work factor set too high can let an attacker exhaust the server's CPU with a large number of login attempts, and as a general rule a hash should take less than one second to calculate.
Password reset security: recovery is a second way in
A password reset lets someone into an account without the password.
That makes it a second login, and an attacker can choose whichever of the two is weaker. API2:2023 says recovery and forgot-password endpoints should be treated as login endpoints for brute force, rate limiting and lockout protections. The Top 10:2025 lists weak or ineffective credential recovery among its authentication failures and says knowledge-based answers cannot be made safe, and MITRE's CWE-640 describes a mechanism that lets users recover or change their password without knowing the original, where that mechanism is weak.
The reset has to demand at least as much as sign-in. WSTG-ATHN-09, OWASP's password change and reset test, notes that sending a reset link to the user's email address without first asking a secret question means relying entirely on the security of that email address.
ASVS 5.0 rules secret questions out, along with password hints (requirement 6.4.2, Level 1), and requirement 6.4.3, at Level 2, asks that the reset process does not bypass any multi-factor authentication that is turned on.
A reset that ends with the user signed in, or with the second factor switched off, is a way round the stronger door.
Rules for the reset link
The Forgot Password Cheat Sheet sets the rules. Tokens come from a cryptographically secure random number generator, are long enough to resist brute force, are linked to one user, are invalidated after use, are stored securely and expire after an appropriate period.
The reset URL is hard-coded or checked against a list of trusted domains rather than built from the request's Host header, and it uses HTTPS. The reset page sends a Referrer Policy of no-referrer to avoid leaking the link through the referrer, and attempts to brute-force tokens are blocked, for example by rate limiting. Nothing about the account, such as a lockout, changes until a valid token is presented.
Once the reset is done, the cheat sheet says to email the user that the password was reset, without the password in the email, and not to sign them in automatically, because that adds complexity to the authentication and session code and makes vulnerabilities more likely. It also says to ask whether to end the user's other sessions, or to end them automatically.
SP 800-63B-4 says account recovery SHALL cause a notification to the subscriber, and that issued recovery codes sent to an email address SHALL be valid for at most 24 hours.
Two more rules from the same sheet stop the reset form becoming a nuisance or a weapon: protect against excessive automated submissions, for example with a per-account rate limit or a CAPTCHA, because otherwise an attacker could flood a user's inbox with reset requests, and do not lock an account in response to a forgotten password attack, because that can be used to deny access to users whose usernames are known.
Email change and reauthentication before sensitive actions
Changing the email address looks like a profile edit, but the address is where reset links go, so whoever changes it controls every future reset.
API2:2023 walks through that chain: an API that lets a client update the account's email address without the current password means someone able to steal an auth token might change the address and then take over the account through the reset password workflow.
That is why the address and the password both sit behind reauthentication. The Authentication Cheat Sheet asks for the current credentials before sensitive account information such as the password or email address is updated, or before sensitive transactions such as shipping a purchase to a new address.
Its reasons: without that check, an attacker may make those changes through cross-site request forgery or cross-site scripting without knowing the password, or after getting temporary physical access to the browser or stealing the session ID.
For password changes it adds the case of a user who signs in on a public computer and forgets to log out.
ASVS 5.0 puts this in three requirements. 6.2.3, at Level 1, asks that password change requires the current and the new password. 7.5.1, at Level 2, asks for full reauthentication before changes to sensitive account attributes that may affect authentication, such as the email address, phone number, MFA configuration or other information used in account recovery. 7.5.3, at Level 3, asks for further authentication with at least one factor, or secondary verification, before highly sensitive transactions or operations.
MITRE's CWE-620, Unverified Password Change, is the weakness when a new password is set without knowledge of the original password or another form of authentication.
Reauthentication should ask for something already bound to the account. The cheat sheet names the current password or a passkey, says not to substitute security questions, and lists account recovery, password resets and critical actions such as changing payment details or adding trusted devices among the events that should trigger it.
A successful reauthentication should also start a new session token, which ASVS 5.0 requirement 7.2.4 asks for at Level 1; the session management guide covers that.
How the email change itself should run
The Authentication Cheat Sheet sets out a process. The user proposes a new address and proves who they are: with multi-factor authentication if it is on, or with the current password if it is not. The new address is stored as a pending change, time-limited nonces are created, and two emails go out.
With MFA on, the current address gets a notification-only message with a link to report unexpected activity, and the new address must confirm.
Without MFA, both addresses must confirm. ASVS 5.0 requirement 6.3.7, at Level 3, asks that users are notified after updates to authentication details such as credential resets or a change of username or email address.
One more leak sits inside this form. If it says "that address is already in use", any signed-in user can check addresses against your user list. No source cited here names this case, but it is the same discrepancy the cheat sheet describes for login, recovery and registration, and the lab's fixed version gives one answer whether the new address is taken or free.
What to log, and what to keep out of the log
Every flow on this page should leave a record.
ASVS 5.0 requirement 16.3.1, at Level 2, asks that all authentication operations are logged, successful and unsuccessful, and says the type of authentication or the factors used should be collected too. Requirement 16.2.1, also at Level 2, asks that each entry carries the metadata an investigation needs, such as when, where, who and what.
The Authentication Cheat Sheet asks that all failures, all password failures and all account lockouts are logged and reviewed. In practice that list covers:
- Sign-in attempts, successful and failed, with the address as submitted, where the request came from and when.
- Sign-up attempts for an address that already has an account, which the page no longer reveals but the log should.
- Reset requests, completed resets, and links refused because they were used or had expired.
- Email change requests, confirmations and refusals, and every password change.
- Failed reauthentication before a sensitive action.
Keeping secrets out of the log
ASVS 5.0 requirement 16.2.5, at Level 2, asks that sensitive data is logged according to its protection level: for example, some data, such as credentials or payment details, may not be allowed in logs, and other data, such as session tokens, may only be logged hashed or masked.
CWE-204's mitigations say highly sensitive information such as passwords should never be saved to log files. Treat a live reset token like a session token, since anyone who reads it can use it.
The lab's event log records the event, the address and the time, and its regression test fails if a password typed into the form shows up in the log.
The log itself becomes a list of who has an account, so protect it like one. ASVS 5.0 requirement 16.4.2, at Level 2, asks that logs are protected from unauthorised access and cannot be modified.
Running the account enumeration lab
The lab is an illustration.
It is a small sign-in service with two invented accounts on example.com, in a flawed version and a fixed version, plus a script that shows what each flow tells an outsider, a script that times repeated requests, and a regression test.
The server binds to 127.0.0.1, lets the system pick a free port, keeps everything in memory and puts email in an in-memory outbox, so nothing leaves your machine. It uses only built-in modules, which Node.js identifies with the node: prefix: node:http, node:crypto, node:test and node:assert.
The Node.js documentation describes built-in modules as compiled into the binary, so there is nothing to install. Passwords are hashed with crypto.scrypt. Use it for learning and for testing code you own.
The flawed version gives itself away three ways: different wording for an address with an account and one without, a different status or redirect, and a timing gap, because it hashes the password only when the account exists and waits for the email provider before it replies.
Its recovery and registration flows also say outright whether an address is registered. The fixed version returns the same message and status on each flow, checks unknown addresses against a dummy record so both paths do comparable work, queues email instead of waiting for it, and asks for the current password before an email or password change.
On the machine it was written on, an Apple M3 Max running Node.js 26.0.0, the flawed login answered an unknown address in a median of 0.2 ms and an address with an account, given a wrong password, in 124.0 ms. The fixed login answered in 126.4 and 127.0 ms, 0.6 ms apart, with each median inside the other's middle half.
Your numbers will differ by machine and from run to run, and a network adds jitter of its own. The gap and its removal are what to look for.
- Save the five files from the asset into an empty folder and open a terminal there.
- Run node show-responses.mjs to see each flow's pair of answers from both versions: status, Location header, whether a session cookie was set, the message, and how many times the password hash ran.
- Run node measure-timing.mjs to time 25 requests per case after three warm-up rounds, for login, recovery and registration, and print the median, middle half and range of each.
- Run node auth-flows.test.mjs, where all 12 tests pass, then node auth-flows.test.mjs flawed, where 11 of the 12 fail and the process exits with code 1, so a pipeline step that runs the test fails.
Why the regression test does not assert on milliseconds
A test that fails when a gap passes some number of milliseconds would fail on a busy build server and pass on a quiet one. The test asserts on what stays the same: the messages, status codes and headers of each pair, that the password hash runs once for an address with an account and once for an address without one, that a reset link works once and does not sign the user in, that the current address hears about an email change, and that a failed sign-in is logged without the password.
The timing script is evidence for a person to read; the test is the guard that stays in the pipeline.
Authentication testing on your own application
The test pack in the asset is written for a team testing its own application.
Run it only against an application you own, or one you are authorised in writing to test, with test accounts created for the purpose, on staging where you can. Probing the sign-in, sign-up or reset forms of a site you do not own, without written authority, is not something this page helps with. The lab measures only its own server on your machine, with invented accounts.
Even on your own system, some checks can do harm. Run lockout, reset and email change checks only on test accounts, never trigger a password reset for a real person's account, and send nothing to a real person's inbox.
Work through the pack flow by flow and keep the evidence each row lists, so a fix can be checked against the same requests later. Decide first which ASVS level you are working to, because some rows, such as consistent timing under requirement 6.3.8, are Level 3 requirements.
Some rows go faster with the code open: which hashing function and settings are used, how reset tokens are generated and stored, and whether every path that signs a user in runs the same checks.
Where an outside test fits
A Clever Ops web application and API penetration test compares sign-up, sign-in and password reset responses for an email address with an account and one without: message text, status code and response time.
Password change and reset are checked for whether one user can change or reset another user's password, whether a reset can be guessed or bypassed, and whether reset skips a multi-factor sign-in that is turned on. Lockout and reset checks run only on test accounts, where the rules of engagement allow them, and no password reset is triggered for a real person's account.
Each finding comes with redacted requests and responses, the accounts that sent them, the steps to reproduce it, a fix and the criteria the retest will use. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
A flaw in how an application decides who someone is. OWASP's Top 10:2025 says the vulnerability is present when an attacker can trick a system into recognising an invalid or incorrect user as legitimate, and its API Security Top 10 names the API version API2:2023 Broken Authentication. It covers the login form and also registration, password recovery, email change and reauthentication, because each of them can let someone into an account or reveal who has one.
It is a weakness that makes other attacks easier. MITRE lists it as CWE-204 for different messages and CWE-208 for different timings, and WSTG-IDNT-04 says a list of valid users can feed a brute force or default password attack. ASVS 5.0 requirement 6.3.8, at Level 3, asks that valid users cannot be deduced from failed sign-ins, for example through messages, status codes or timing, while the OWASP Authentication Cheat Sheet asks for a generic message in login, password reset and password recovery and says registration can take the same approach, and the Top 10 asks for the same messages in registration, credential recovery and API pathways.
The OWASP Authentication Cheat Sheet gives "A link to activate your account has been emailed to the address provided." as the correct reply and "This user ID is already in use." as an incorrect one. That leaves any difference to the email, which is this guide's suggestion and not the cheat sheet's. The cheat sheet accepts that generic messages have a usability cost, says the choice can depend on how critical the application and its data are, and suggests a CAPTCHA where a generic message cannot be used.
Do the same work on every path. Hash the submitted password even when no account matches, for example against a dummy record with the same settings, and send emails after the reply rather than before it. Then measure: send each case repeatedly against your own staging system and compare the medians and spread, and keep a regression test that checks the hash runs on both paths.
Because the email address is where reset links go. API2:2023 describes an attacker with a stolen token changing the address and then taking the account through the reset flow. ASVS 5.0 requirement 7.5.1, at Level 2, asks for full reauthentication before the email address or other recovery details change, and the OWASP Authentication Cheat Sheet adds a confirmation from the new address and a message to the old one.
The OWASP Forgot Password Cheat Sheet asks for a token from a secure random generator, long enough to resist guessing, tied to one user, stored securely, single use and with an expiry, sent in a link built from your own domain rather than the request's Host header. The reset should not sign the user in automatically and should not bypass a second factor, which ASVS 5.0 requirement 6.4.3 asks at Level 2.
Every authentication attempt, successful or not, with the metadata an investigation needs, such as when, where, who and what, as ASVS 5.0 requirements 16.3.1 and 16.2.1 ask at Level 2, plus reset requests, email and password changes, and failed reauthentication. Keep passwords and live tokens out: requirement 16.2.5 says that, by protection level, some data such as credentials may not be allowed in logs, and CWE-204 says passwords should never be saved to log files.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.