Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🔑 fix: Stringify Ban Cache Keys When Redis Is Off (#16039)

GokayAIf80f0be90e51
diff --git a/api/cache/logViolation.js b/api/cache/logViolation.js
index 1ff65c6ccd..fd2549c58d 100644
--- a/api/cache/logViolation.js
+++ b/api/cache/logViolation.js
@@ -13,7 +13,7 @@ const banViolation = require('./banViolation');
* @param {number | string} [score=1] - The severity of the violation. Defaults to 1
*/
const logViolation = async (req, res, type, errorMessage, score = 1) => {
- const userId = req.user?.id ?? req.user?._id;
+ const userId = req.user?.id ?? req.user?._id?.toString();
if (!userId) {
return;
}
diff --git a/api/server/middleware/checkBan.js b/api/server/middleware/checkBan.js
index 7194a555b0..0871e51c04 100644
--- a/api/server/middleware/checkBan.js
+++ b/api/server/middleware/checkBan.js
@@ -88,7 +88,7 @@ const checkBan = async (req, res, next = () => {}) => {
}
req.ip = removePorts(req);
- let userId = req.user?.id ?? req.user?._id ?? null;
+ let userId = req.user?.id ?? req.user?._id?.toString() ?? null;
if (!userId && req?.body?.email) {
const user = await findUser({ email: req.body.email }, '_id');
diff --git a/api/server/middleware/checkBan.spec.js b/api/server/middleware/checkBan.spec.js
new file mode 100644
index 0000000000..ee83f0bef8
--- /dev/null
+++ b/api/server/middleware/checkBan.spec.js
@@ -0,0 +1,96 @@
+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));
+ });
+});
diff --git a/api/test/server/middleware/checkBan.test.js b/api/test/server/middleware/checkBan.test.js
index 237282d9d0..39775c389a 100644
--- a/api/test/server/middleware/checkBan.test.js
+++ b/api/test/server/middleware/checkBan.test.js
@@ -401,6 +401,55 @@ describe('checkBan middleware', () => {
});
});
+ describe('non-string cache keys (#16025)', () => {
+ const objectIdHex = '507f1f77bcf86cd799439011';
+ const objectId = {
+ toString() {
+ return objectIdHex;
+ },
+ };
+
+ it('stringifies ObjectId user keys when Redis is off', async () => {
+ const next = jest.fn();
+ const req = createReq({ user: { _id: objectId } });
+
+ await checkBan(req, createRes(), next);
+
+ expect(next).toHaveBeenCalledWith();
+ expect(mockBanCacheGet).toHaveBeenCalledWith(objectIdHex);
+ expect(mockBanLogsGet).toHaveBeenCalledWith(objectIdHex);
+ for (const [key] of mockBanCacheGet.mock.calls) {
+ expect(typeof key).toBe('string');
+ }
+ });
+
+ it('stringifies numeric user keys when Redis is off', async () => {
+ await checkBan(createReq({ user: { _id: 12345 } }), createRes(), jest.fn());
+
+ expect(mockBanCacheGet).toHaveBeenCalledWith('12345');
+ expect(mockBanLogsGet).toHaveBeenCalledWith('12345');
+ });
+
+ it('stringifies ObjectId user keys in Redis-prefixed cache lookups', async () => {
+ process.env.USE_REDIS = 'true';
+
+ await checkBan(createReq({ user: { _id: objectId } }), createRes(), jest.fn());
+
+ expect(mockBanCacheGet).toHaveBeenCalledWith(`ban_cache:user:${objectIdHex}`);
+ expect(mockBanLogsGet).toHaveBeenCalledWith(objectIdHex);
+ });
+
+ it('stringifies ObjectId user keys from email lookup', async () => {
+ findUser.mockResolvedValueOnce({ _id: objectId });
+ const req = createReq({ user: null, body: { email: '[email protected]' } });
+
+ await checkBan(req, createRes(), jest.fn());
+
+ expect(mockBanCacheGet).toHaveBeenCalledWith(objectIdHex);
+ expect(mockBanLogsGet).toHaveBeenCalledWith(objectIdHex);
+ });
+ });
+
describe('Redis key paths (Finding 2 regression)', () => {
beforeEach(() => {
process.env.USE_REDIS = 'true';