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 <noreply@anthropic.com>
This commit is contained in:
Kamil KaliszandClaude Opus 5.5 committed 2026-11-18 17:33:53 +01:00
1 parent e99b42c387
commit 363de086fc
3 files changed
+76 -4

No files matched your search

+26 -3
View File
@@ -66,6 +66,12 @@ function sendAuthRateLimit(reply: FastifyReply, failures: StaleExpirationMap<str
reply.code(429).send('Too Many Requests — try again later');
}
/** 401 with a Basic challenge, so a browser shows its login dialog. */
function challengeBasicAuth(reply: FastifyReply): void {
reply.header('WWW-Authenticate', 'Basic realm="Codeman"');
reply.code(401).send('Unauthorized');
}
/** Parse a `Basic base64(user:pass)` header into its parts, or null if malformed. */
function parseBasicAuth(header?: string): { username: string; password: string } | null {
if (!header || !header.startsWith('Basic ')) return null;
@@ -485,6 +491,16 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
return;
}
// No credentials at all is not a guess: challenge it without counting or limiting.
// Counting it locked users out after every server restart (cookie sessions live in
// memory): an open tab's background requests carry only the dead cookie, ten of them
// filled the bucket within seconds, and the 429 that followed never re-prompted the
// browser for a password, so reloading could not recover until the window expired.
if (!auth) {
challengeBasicAuth(reply);
return;
}
// Rate limit only requests that failed to authenticate on this attempt.
const failures = authFailures.get(clientIp) ?? 0;
if (failures >= 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);
});
}
+28
View File
@@ -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', () => {
+22 -1
View File
@@ -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';