From 363de086fce46b8bc8925c508cee70f75f3db84e Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Wed, 18 Nov 2026 17:33:53 +0100 Subject: [PATCH] fix(auth): stop counting credential-less requests as failed logins After a server restart every cookie session is gone (they live in memory). An open tab's background requests then carry only the dead cookie and no Authorization header. Each one was counted as a failed login: ten filled the single-user per-IP bucket within seconds, and the 429 that followed carries no WWW-Authenticate challenge, so the browser never showed its login dialog again and reloading could not recover for 15 minutes. Behind a tunnel all clients share 127.0.0.1, so every device was locked out. Multi-user mode had the same shape against its per-IP pre-gate, which refuses even a correct password once full. A request with no Authorization header is not a guess and runs no password check, so it is now challenged with a plain 401 and not counted, in both modes and even while the IP is limited. Wrong and malformed credentials are counted and limited exactly as before. Co-Authored-By: Claude Opus 5.5 --- src/web/middleware/auth.ts | 29 ++++++++++++++++++++++++++--- test/auth-security.test.ts | 28 ++++++++++++++++++++++++++++ test/multiuser-auth.test.ts | 23 ++++++++++++++++++++++- 3 files changed, 76 insertions(+), 4 deletions(-) diff --git a/src/web/middleware/auth.ts b/src/web/middleware/auth.ts index ea7c7767..e1c0bcad 100644 --- a/src/web/middleware/auth.ts +++ b/src/web/middleware/auth.ts @@ -66,6 +66,12 @@ function sendAuthRateLimit(reply: FastifyReply, failures: StaleExpirationMap= AUTH_FAILURE_MAX) { @@ -703,6 +719,14 @@ function registerMultiUserAuthHook( // which is every reload after a restart: cookie sessions live in memory, so the // browser replays its cached Basic header on many parallel requests at once. A // request with no verify in flight for its credentials is gated as normal. + // No Authorization header at all is not a guess and runs no scrypt: challenge it + // before the gates, without counting. Counting it let an open tab's background + // requests after a restart (cookie sessions live in memory) fill the per-IP bucket, + // which then refused even the correct password, and a 429 never re-prompts a browser. + if (!req.headers.authorization) { + challengeBasicAuth(reply); + return; + } const creds = parseBasicAuth(req.headers.authorization); const normUser = creds ? creds.username.trim().toLowerCase() : ''; const flightKey = creds ? verifyFlightKey(clientIp, normUser, creds.password) : ''; @@ -746,10 +770,9 @@ function registerMultiUserAuthHook( return; } - // No credentials presented: count against the per-IP bucket and challenge. + // A malformed Authorization header: count against the per-IP bucket and challenge. authFailures.set(clientIp, ipFail + 1); - reply.header('WWW-Authenticate', 'Basic realm="Codeman"'); - reply.code(401).send('Unauthorized'); + challengeBasicAuth(reply); }); } diff --git a/test/auth-security.test.ts b/test/auth-security.test.ts index 712bd5f5..83dd208d 100644 --- a/test/auth-security.test.ts +++ b/test/auth-security.test.ts @@ -244,6 +244,34 @@ describe('Auth Security', () => { expect(wrongAfterRecovery.status).toBe(401); }); + + it('should not count requests without credentials (restart with a tab open)', async () => { + // After a restart the open tab's background requests carry only a dead cookie. + for (let i = 0; i < AUTH_FAILURE_MAX * 3; i++) { + const res = await fetch(`${rateBaseUrl}/api/status`, { + headers: { Cookie: 'codeman_session=stale-from-before-restart' }, + }); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toBe('Basic realm="Codeman"'); + } + + // None of them were guesses: the wrong-password bucket is still empty. + await exhaustAuthFailures(rateBaseUrl, 'cod-no-creds'); + }); + + it('should keep challenging requests without credentials during lockout', async () => { + await exhaustAuthFailures(rateBaseUrl, 'cod-challenge'); + + // A 429 never makes a browser show its login dialog; a 401 challenge does. + const res = await fetch(`${rateBaseUrl}/api/status`); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toBe('Basic realm="Codeman"'); + + const wrong = await fetch(`${rateBaseUrl}/api/status`, { + headers: { Authorization: basicAuthHeader(TEST_USER, 'still-wrong') }, + }); + expect(wrong.status).toBe(429); + }); }); describe('Hook Event Endpoint', () => { diff --git a/test/multiuser-auth.test.ts b/test/multiuser-auth.test.ts index 196e779e..e73c8309 100644 --- a/test/multiuser-auth.test.ts +++ b/test/multiuser-auth.test.ts @@ -112,7 +112,7 @@ async function startIpServer() { const app = (s as unknown as { app: FastifyInstance }).app; const login = (ip: string, user: string, pass: string) => app.inject({ method: 'GET', url: '/api/status', headers: { authorization: basic(user, pass) }, remoteAddress: ip }); - return { login, buckets: s as unknown as FailureBuckets }; + return { app, login, buckets: s as unknown as FailureBuckets }; } describe('multi-user auth', () => { @@ -270,6 +270,27 @@ describe('multi-user auth', () => { expect((await login(ipA, 'bob', 'bobpass123')).statusCode).toBe(429); }); + it('requests without credentials are challenged, not counted, even past the per-IP cap', async () => { + const { app, login, buckets } = await startIpServer(); + const ip = '203.0.113.40'; + const bare = () => + app.inject({ + method: 'GET', + url: '/api/status', + headers: { cookie: 'codeman_session=stale-from-before-restart' }, + remoteAddress: ip, + }); + + // An open tab after a restart: many cookie-only requests, none of them a guess. + for (let i = 0; i < AUTH_IP_FAILURE_MAX + 5; i++) { + const res = await bare(); + expect(res.statusCode, `request ${i + 1}`).toBe(401); + expect(res.headers['www-authenticate']).toBe('Basic realm="Codeman"'); + } + expect(buckets.authFailures.get(ip)).toBeUndefined(); + expect((await login(ip, 'alice', 'alicepass1')).statusCode).toBe(200); + }); + it('per-IP pre-gate: a concurrent burst from one IP reaches the verify at most AUTH_IP_FAILURE_MAX times', async () => { const { login, buckets } = await startIpServer(); const ip = '203.0.113.40';