diff --git a/src/backend/core/http/expressAugmentation.ts b/src/backend/core/http/expressAugmentation.ts index 25b9b0ce9..5e2b7f7c5 100644 --- a/src/backend/core/http/expressAugmentation.ts +++ b/src/backend/core/http/expressAugmentation.ts @@ -50,6 +50,13 @@ declare global { tokenAuthFailed?: boolean; + /** + * What `authenticate` threw while checking the token (a database + * failure, say). The token may be fine; gates rethrow this instead + * of answering 401. + */ + tokenAuthError?: unknown; + /** * Set when a token authenticated but its app is on the origin * blocklist. The auth probe leaves `actor` unset; gates translate diff --git a/src/backend/core/http/middleware/authProbe.http.test.ts b/src/backend/core/http/middleware/authProbe.http.test.ts new file mode 100644 index 000000000..316d06dce --- /dev/null +++ b/src/backend/core/http/middleware/authProbe.http.test.ts @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { setupPuterTestEnv, type PuterTestEnv } from '../../../testUtil.js'; + +const loadShed = () => + Object.assign(new Error('Database operation failed'), { + code: 'dbBatchFailed', + }); + +/** + * A token whose lookup fails is not a dead token: clients discard a token on + * 401 `token_auth_failed`, so that answer is kept for tokens that checked out + * invalid. + */ +describe('auth probe when the token lookup fails', () => { + let env: PuterTestEnv; + + beforeAll(async () => { + env = await setupPuterTestEnv(); + }, 120_000); + + afterAll(async () => { + await env?.shutdown(); + }); + + const get = (path: string, token: string) => + fetch(new URL(path, env.apiOrigin), { + headers: { authorization: `Bearer ${token}` }, + }); + + /** Run `fn` while the next user lookup rejects with `error`. */ + const withFailedUserLookup = async ( + error: Error, + fn: () => Promise, + ): Promise => { + const spy = vi + .spyOn(env.server.stores.user, 'getByUuid') + .mockRejectedValueOnce(error); + try { + return await fn(); + } finally { + spy.mockRestore(); + } + }; + + it.each([ + ['a session token', () => env.users.user.token], + ['an access token', () => env.users.user.apiToken], + ])( + 'answers %s with 503 db_unavailable during a database outage', + async (_kind, tokenOf) => { + const token = tokenOf(); + const res = await withFailedUserLookup(loadShed(), () => + get('/whoami', token), + ); + expect(res.status).toBe(503); + expect(res.headers.get('retry-after')).toBe('5'); + expect(await res.json()).toEqual({ + error: 'Service temporarily unavailable', + message: 'Service temporarily unavailable', + code: 'db_unavailable', + }); + + expect((await get('/whoami', token)).status).toBe(200); + }, + ); + + it('answers an unexpected lookup failure with a generic 500, not a 401', async () => { + const res = await withFailedUserLookup(new Error('boom'), () => + get('/whoami', env.users.user.token), + ); + expect(res.status).toBe(500); + expect((await res.json()).code).toBe('internal_error'); + }); + + it('serves a route that does not require auth anonymously', async () => { + const res = await withFailedUserLookup(loadShed(), () => + get('/version', env.users.user.token), + ); + expect(res.status).toBe(200); + }); + + it('still answers an invalid token with 401 token_auth_failed', async () => { + const res = await get('/whoami', 'not-a-real-jwt'); + expect(res.status).toBe(401); + expect(await res.json()).toEqual({ + error: 'Authentication failed', + message: 'Authentication failed', + code: 'token_auth_failed', + }); + }); +}); diff --git a/src/backend/core/http/middleware/authProbe.test.ts b/src/backend/core/http/middleware/authProbe.test.ts index be4874e11..09fe27f12 100644 --- a/src/backend/core/http/middleware/authProbe.test.ts +++ b/src/backend/core/http/middleware/authProbe.test.ts @@ -555,17 +555,18 @@ describe('createAuthProbe — actor attachment + failure tracking', () => { expect(req.tokenAuthFailed).toBe(true); }); - it('never rejects — sets tokenAuthFailed even when AuthService throws', async () => { + it('never rejects — records the error, not tokenAuthFailed, when AuthService throws', async () => { const stub = makeStubAuth(); stub.setNext('throw'); const probe = createAuthProbe({ authService: stub.service }); const { req, next } = await runProbe( probe, - makeReq({ headers: { authorization: 'Bearer bad-tok' } }), + makeReq({ headers: { authorization: 'Bearer some-tok' } }), ); // Critical invariant: the probe NEVER rejects, no matter what. expect(next).toHaveBeenCalledWith(); - expect(req.tokenAuthFailed).toBe(true); + expect(req.tokenAuthFailed).toBeUndefined(); + expect(req.tokenAuthError).toBeInstanceOf(Error); expect(req.actor).toBeUndefined(); }); @@ -880,4 +881,27 @@ describe('createAuthProbe (integration) — real session token → real actor', expect(req.actor).toBeUndefined(); expect(req.tokenAuthFailed).toBe(true); }); + + it('records a failed user lookup on a valid token without marking it invalid', async () => { + const user = await makeUser(); + const { token } = await authService.createSessionToken(user); + const lookupError = Object.assign(new Error('db down'), { + code: 'dbBatchFailed', + }); + const spy = vi + .spyOn(server.stores.user, 'getByUuid') + .mockRejectedValueOnce(lookupError); + try { + const probe = createAuthProbe({ authService }); + const { req } = await runProbe( + probe, + makeReq({ headers: { authorization: `Bearer ${token}` } }), + ); + expect(req.actor).toBeUndefined(); + expect(req.tokenAuthFailed).toBeUndefined(); + expect(req.tokenAuthError).toBe(lookupError); + } finally { + spy.mockRestore(); + } + }); }); diff --git a/src/backend/core/http/middleware/authProbe.ts b/src/backend/core/http/middleware/authProbe.ts index f06cc24ca..1de35c831 100644 --- a/src/backend/core/http/middleware/authProbe.ts +++ b/src/backend/core/http/middleware/authProbe.ts @@ -45,9 +45,9 @@ interface AuthProbeOptions { * and valid — attaches an `Actor` to `req.actor`. * * Key property: this middleware **never rejects**. Missing tokens, malformed - * tokens, expired tokens, tokens pointing at deleted users — all result in - * `req.actor` being left undefined. Per-route gates decide whether absence is - * acceptable. + * tokens, expired tokens, tokens pointing at deleted users, and lookups that + * fail outright all result in `req.actor` being left undefined. Per-route gates + * decide whether absence is acceptable. * * Token lookup order: * @@ -153,8 +153,10 @@ export const createAuthProbe = (opts: AuthProbeOptions): RequestHandler => { } else if (result.invalid) { req.tokenAuthFailed = true; } - } catch { - req.tokenAuthFailed = true; + } catch (err) { + // Not a verdict on the token: routes that require auth answer + // with this error, routes that don't serve the request anonymously. + req.tokenAuthError = err; } next(); }; diff --git a/src/backend/core/http/middleware/gates.test.ts b/src/backend/core/http/middleware/gates.test.ts index 53bfa6b08..99a734420 100644 --- a/src/backend/core/http/middleware/gates.test.ts +++ b/src/backend/core/http/middleware/gates.test.ts @@ -288,6 +288,22 @@ describe('requireAuthGate', () => { }); expectHttpError(got, 401, 'reauth_required'); }); + + it('passes on the error when the token could not be checked', () => { + const lookupError = Object.assign(new Error('down'), { + code: 'dbBatchFailed', + }); + const got = runGate(requireAuthGate(), { tokenAuthError: lookupError }); + expect(got).toBe(lookupError); + }); + + it('still answers token_auth_failed when a check found the token invalid', () => { + const got = runGate(requireAuthGate(), { + tokenAuthFailed: true, + tokenAuthError: new Error('down'), + }); + expectHttpError(got, 401, 'token_auth_failed'); + }); }); // ── requireUserActorGate ──────────────────────────────────────────── @@ -330,6 +346,14 @@ describe('requireUserActorGate', () => { expectHttpError(got, 401, 'token_missing'); }); + it('passes on the error when the token could not be checked', () => { + const lookupError = new Error('down'); + const got = runGate(requireUserActorGate(), { + tokenAuthError: lookupError, + }); + expect(got).toBe(lookupError); + }); + it('rejects a FULL-ACCESS access token too — account routes stay closed', () => { // The account wall is actor-type based: even a full-access PAT (which // the resource wall lets through) is rejected here, so it can never diff --git a/src/backend/core/http/middleware/gates.ts b/src/backend/core/http/middleware/gates.ts index 79c36d9d0..cf6938ccd 100644 --- a/src/backend/core/http/middleware/gates.ts +++ b/src/backend/core/http/middleware/gates.ts @@ -50,7 +50,7 @@ import { assertVerifiedEmail } from '../verifiedEmail'; // Make sure the `Express.Request.actor` augmentation is in scope. import '../expressAugmentation'; -const rejectAuth = (req: Request): HttpError => { +const rejectAuth = (req: Request): unknown => { if (req.requiresReauth) { return new HttpError(401, 'Re-authentication required', { legacyCode: 'reauth_required', @@ -71,6 +71,9 @@ const rejectAuth = (req: Request): HttpError => { legacyCode: 'token_auth_failed', }); } + // The token couldn't be checked, so a 401 would wrongly tell the client + // to discard it; the error handler answers (503 for a database outage). + if (req.tokenAuthError !== undefined) return req.tokenAuthError; return new HttpError(401, 'Missing authentication token', { legacyCode: 'token_missing', }); diff --git a/src/backend/services/socket/SocketService.test.ts b/src/backend/services/socket/SocketService.test.ts index 843c6ed2b..43c9ed2f7 100644 --- a/src/backend/services/socket/SocketService.test.ts +++ b/src/backend/services/socket/SocketService.test.ts @@ -963,6 +963,31 @@ describe('SocketService (live socket.io)', () => { socket.disconnect(); }); + it('keeps a connection up when its re-check lookup fails', async () => { + const user = await createTestUser(server, { + username: 'sock-lookup-down', + password: 'sock-lookup-down-password', + }); + const socket = await connect({ auth_token: `Bearer ${user.token}` }); + const authenticate = vi + .spyOn(server.services.auth, 'authenticate') + .mockRejectedValue( + Object.assign(new Error('Database operation failed'), { + code: 'dbBatchFailed', + }), + ); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + await socketService.reauthenticateSockets(); + await new Promise((r) => setTimeout(r, 200)); + expect(socket.connected).toBe(true); + } finally { + authenticate.mockRestore(); + warn.mockRestore(); + socket.disconnect(); + } + }); + it('re-checks without recording session activity', async () => { const idle = await createTestUser(server, { username: 'sock-idle', diff --git a/src/backend/services/socket/SocketService.ts b/src/backend/services/socket/SocketService.ts index dd7be67fd..2ac61c6d2 100644 --- a/src/backend/services/socket/SocketService.ts +++ b/src/backend/services/socket/SocketService.ts @@ -982,15 +982,22 @@ export class SocketService extends PuterService { }, ); const decisions = new Map(); + let unchecked = 0; checked.forEach((token, i) => { const outcome = outcomes[i]; - decisions.set( - token, - outcome?.status === 'fulfilled' - ? outcome.value - : { reject: new Error('socket reauth failed') }, - ); + // A lookup that failed says nothing about the credential, so its + // sockets stay up until a later sweep gets an answer. + if (outcome?.status === 'fulfilled') { + decisions.set(token, outcome.value); + } else { + unchecked++; + } }); + if (unchecked > 0) { + console.warn( + `[socket] reauth sweep could not check ${unchecked} credential(s)`, + ); + } for (const socket of sockets) { const decision = socket.authToken