LibreChat/packages/api/src/apiKeys/middleware.auth.spec.ts
Marco Beretta 4c6ea7e981
🔐 fix: Hash Passwords on a Worker Pool and Surface API Key Lookup Failures (#17261)
* fix: Hash Off the Event Loop and Surface API Key Lookup Failures

Registration, email verification, password reset and verification resends
hashed and compared with bcryptjs's synchronous calls. bcryptjs is pure
JavaScript, so each call blocked the event loop for every request in the
process. They now use the promise APIs, and the password reset
dependencies are async.

validateAgentApiKey caught its own query failures and returned null, so a
database outage answered remote callers with 401 Invalid API key. It now
lets the failure reach requireApiKeyAuth, which answers with a 500.

* fix: Run bcrypt on a Worker Pool in packages/api

bcryptjs's promise API still computes on the main thread, only in chunks
of up to 100 ms, so concurrent registrations and resets kept stalling
unrelated requests (four cost-10 hashes delayed a 5 ms timer by about
190 ms). hashSecret and compareSecret now run bcryptjs on a small
worker_threads pool in packages/api, and AuthService.js calls them.

* feat: Configure the Password Hashing Worker Count

* fix: Verify Login and Step-Up Passwords on the Hash Pool
2026-10-19 22:13:31 +02:00

171 lines
5.8 KiB
TypeScript

import { Types } from 'mongoose';
import { TWO_FACTOR_ENROLLMENT_REQUIRED_CODE } from 'librechat-data-provider';
import type { NextFunction, Response } from 'express';
import type { ApiKeyAuthRequest } from './middleware';
import { createRequireApiKeyAuth } from './middleware';
function createResponse(): {
res: Response;
status: jest.Mock;
json: jest.Mock;
} {
const status = jest.fn();
const json = jest.fn();
const res = { status, json } as unknown as Response;
status.mockReturnValue(res);
return { res, status, json };
}
function createRequest(): ApiKeyAuthRequest {
return {
headers: { authorization: 'Bearer lc-key' },
} as ApiKeyAuthRequest;
}
describe('remote Agent API key authentication', () => {
it('rejects a valid key while account deletion is fenced', async () => {
const userId = new Types.ObjectId();
const middleware = createRequireApiKeyAuth({
validateAgentApiKey: jest.fn().mockResolvedValue({
userId,
keyId: new Types.ObjectId(),
}),
findUser: jest.fn().mockResolvedValue({ _id: userId }),
isPrincipalActive: jest.fn().mockResolvedValue(false),
});
const { res, status, json } = createResponse();
const next = jest.fn() as NextFunction;
await middleware(createRequest(), res, next);
expect(status).toHaveBeenCalledWith(409);
expect(json).toHaveBeenCalledWith({
error: {
message: 'Account deletion is in progress',
type: 'invalid_request_error',
code: 'account_deletion_in_progress',
},
});
expect(next).not.toHaveBeenCalled();
});
it('admits an active principal', async () => {
const userId = new Types.ObjectId();
const middleware = createRequireApiKeyAuth({
validateAgentApiKey: jest.fn().mockResolvedValue({
userId,
keyId: new Types.ObjectId(),
}),
findUser: jest.fn().mockResolvedValue({ _id: userId }),
isPrincipalActive: jest.fn().mockResolvedValue(true),
});
const req = createRequest();
const { res } = createResponse();
const next = jest.fn() as NextFunction;
await middleware(req, res, next);
expect(req.user?.id).toBe(userId.toString());
expect(next).toHaveBeenCalledWith();
});
describe('under required two-factor enforcement', () => {
const original = process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION;
beforeEach(() => {
process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = 'true';
});
afterEach(() => {
if (original === undefined) {
delete process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION;
} else {
process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION = original;
}
});
const authenticate = async (owner: Record<string, unknown>) => {
const userId = new Types.ObjectId();
const middleware = createRequireApiKeyAuth({
validateAgentApiKey: jest.fn().mockResolvedValue({ userId, keyId: new Types.ObjectId() }),
findUser: jest.fn().mockResolvedValue({ _id: userId, ...owner }),
isPrincipalActive: jest.fn().mockResolvedValue(true),
});
const req = createRequest();
const response = createResponse();
const next = jest.fn() as NextFunction;
await middleware(req, response.res, next);
return { req, next, ...response };
};
it('refuses a key whose local owner has not enrolled', async () => {
const { req, next, status, json } = await authenticate({ provider: 'local' });
expect(status).toHaveBeenCalledWith(403);
expect(json).toHaveBeenCalledWith({
error: expect.objectContaining({ code: TWO_FACTOR_ENROLLMENT_REQUIRED_CODE }),
});
expect(req.user).toBeUndefined();
expect(next).not.toHaveBeenCalled();
});
it('admits a key whose owner has enrolled', async () => {
const { next } = await authenticate({ provider: 'local', twoFactorEnabled: true });
expect(next).toHaveBeenCalledWith();
});
it('admits a key whose owner signs in through a federated provider', async () => {
const { next } = await authenticate({ provider: 'openid' });
expect(next).toHaveBeenCalledWith();
});
});
it('starts the user and deletion-fence reads together', async () => {
const userId = new Types.ObjectId();
let resolveUser!: (user: { _id: Types.ObjectId }) => void;
const user = new Promise<{ _id: Types.ObjectId }>((resolve) => {
resolveUser = resolve;
});
const findUser = jest.fn().mockReturnValue(user);
const isPrincipalActive = jest.fn().mockResolvedValue(true);
const middleware = createRequireApiKeyAuth({
validateAgentApiKey: jest.fn().mockResolvedValue({
userId,
keyId: new Types.ObjectId(),
}),
findUser,
isPrincipalActive,
});
const { res } = createResponse();
const next = jest.fn() as NextFunction;
const authentication = middleware(createRequest(), res, next);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(findUser).toHaveBeenCalledTimes(1);
expect(isPrincipalActive).toHaveBeenCalledWith(userId.toString());
expect(next).not.toHaveBeenCalled();
resolveUser({ _id: userId });
await authentication;
expect(next).toHaveBeenCalledWith();
});
it('answers a failed key lookup with a server error, not an invalid key', async () => {
const middleware = createRequireApiKeyAuth({
validateAgentApiKey: jest.fn().mockRejectedValue(new Error('connection reset')),
findUser: jest.fn(),
isPrincipalActive: jest.fn(),
});
const { res, status, json } = createResponse();
const next = jest.fn() as NextFunction;
await middleware(createRequest(), res, next);
expect(status).toHaveBeenCalledWith(500);
expect(json).toHaveBeenCalledWith(
expect.objectContaining({ error: expect.objectContaining({ code: 'internal_error' }) }),
);
expect(next).not.toHaveBeenCalled();
});
});