LibreChat/api/server/middleware/checkBan.spec.js
GokayAI f80f0be90e
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
🔑 fix: Stringify Ban Cache Keys When Redis Is Off (#16039)
* 🔑 fix: Stringify Ban Cache Keys When Redis Is Off

Keyv/Mongo throws when checkBan passes a raw ObjectId as the cache key
with Redis disabled, which 500s every social OAuth login.

Fixes #16025

Signed-off-by: GokayAI <60583610+gokay-ai@users.noreply.github.com>

* 🔑 fix: Stringify Violation Log Keys and Cover Bans With Real Keyv

logViolation keyed its violation and ban logs by the raw
`req.user.id ?? req.user._id`, the same shape checkBan used, so a lean
user document would hit the same keyv 5.6 `key.startsWith` TypeError on
the namespaced violation stores and record its ban under an ObjectId.

The new spec drives checkBan and logViolation through real namespaced
Keyv instances (Mongo-backed ban store, in-memory violation logs) with
an ObjectId-only OAuth user: an unbanned user passes, and a ban logged
from one address is enforced for the same user from another.

* 🎯 refactor: Stringify Only the ObjectId Fallback for Ban Keys

The id is converted once, where a non-string can enter: the lean
document's `_id` fallback. `req.user.id` is already a string on every
path that sets it (the JWT strategies, Mongoose's `id` virtual, the 2FA
limiter's temp-token id), and the email lookup already stringifies, so
`getBanCacheKey` and that line go back to their dev form.

---------

Signed-off-by: GokayAI <60583610+gokay-ai@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-19 15:52:06 -04:00

96 lines
3.2 KiB
JavaScript

const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');
const { ErrorTypes, ViolationTypes } = require('librechat-data-provider');
/** Violation logs are file-backed in production; keep the real namespaced Keyv, swap only the store. */
jest.mock('~/cache/getLogStores', () => {
const { Keyv } = jest.requireActual('keyv');
const { ViolationTypes } = jest.requireActual('librechat-data-provider');
const getLogStores = jest.requireActual('~/cache/getLogStores');
const violationLogs = new Map();
return (type) => {
if (type === ViolationTypes.BAN) {
return getLogStores(type);
}
if (!violationLogs.has(type)) {
const namespace = type === ViolationTypes.GENERAL ? 'violations' : `violations:${type}`;
violationLogs.set(type, new Keyv({ store: new Map(), namespace }));
}
return violationLogs.get(type);
};
});
jest.mock('~/models', () => ({
...jest.requireActual('~/models'),
deleteAllUserSessions: jest.fn().mockResolvedValue(true),
}));
process.env.BAN_VIOLATIONS = 'true';
process.env.BAN_INTERVAL = '20';
delete process.env.USE_REDIS;
const logViolation = require('~/cache/logViolation');
const checkBan = require('./checkBan');
/** Passport's social strategies hand the callback a lean user: an ObjectId `_id` and no `id`. */
const createOAuthCallbackReq = (userId, ip) => ({
ip,
user: { _id: userId },
method: 'GET',
headers: { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/140.0.0.0' },
body: {},
baseUrl: '/oauth',
originalUrl: '/oauth/google/callback',
isOAuthNavigation: true,
});
const createRes = () => ({
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
redirect: jest.fn().mockReturnThis(),
clearCookie: jest.fn(),
});
describe('checkBan with namespaced Keyv stores and ObjectId user ids', () => {
let mongoServer;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
await mongoose.connect(mongoServer.getUri());
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
it('lets an unbanned OAuth user through without Redis', async () => {
const next = jest.fn();
const req = createOAuthCallbackReq(new mongoose.Types.ObjectId(), '10.0.0.1');
await checkBan(req, createRes(), next);
expect(next).toHaveBeenCalledTimes(1);
expect(next).toHaveBeenCalledWith();
expect(req.banned).toBeUndefined();
});
it('enforces a ban recorded for the same user from another address', async () => {
const userId = new mongoose.Types.ObjectId();
const violationReq = createOAuthCallbackReq(userId, '10.0.0.2');
const errorMessage = { type: ViolationTypes.LOGINS };
await logViolation(violationReq, createRes(), ViolationTypes.LOGINS, errorMessage, 20);
expect(errorMessage.ban).toBe(true);
const next = jest.fn();
const res = createRes();
const req = createOAuthCallbackReq(new mongoose.Types.ObjectId(userId.toString()), '10.0.0.3');
await checkBan(req, res, next);
expect(next).not.toHaveBeenCalled();
expect(req.banned).toBe(true);
expect(res.redirect).toHaveBeenCalledWith(expect.stringContaining(ErrorTypes.AUTH_BANNED));
});
});