mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-03-24 00:26:34 +01:00
♾️ fix: Permanent Ban Cache and Expired Ban Cleanup Defects (#12324)
* fix: preserve ban data object in checkBan to prevent permanent cache The !! operator on line 108 coerces the ban data object to a boolean, losing the expiresAt property. This causes: 1. Number(true.expiresAt) = NaN → expired bans never cleaned from banLogs 2. banCache.set(key, true, NaN) → Keyv stores with expires: null (permanent) 3. IP-based cache entries persist indefinitely, blocking unrelated users Fix: replace isBanned (boolean) with banData (original object) so that expiresAt is accessible for TTL calculation and proper cache expiry. * fix: address checkBan cleanup defects exposed by ban data fix The prior commit correctly replaced boolean coercion with the ban data object, but activated previously-dead cleanup code with several defects: - IP-only expired bans fell through cleanup without returning next(), re-caching with negative TTL (permanent entry) and blocking the user - Redis deployments used cache-prefixed keys for banLogs.delete(), silently failing since bans are stored at raw keys - banCache.set() calls were fire-and-forget, silently dropping errors - No guard for missing/invalid expiresAt reproduced the NaN TTL bug on legacy ban records Consolidate expired-ban cleanup into a single block that always returns next(), use raw keys (req.ip, userId) for banLogs.delete(), add an expiresAt validity guard, await cache writes with error logging, and parallelize independent I/O with Promise.all. Add 25 tests covering all checkBan code paths including the specific regressions for IP-only cleanup, Redis key mismatch, missing expiresAt, and cache write failures. --------- Co-authored-by: Danny Avila <danny@librechat.ai>
This commit is contained in:
parent
96f6976e00
commit
54fc9c2c99
2 changed files with 469 additions and 38 deletions
|
|
@ -10,6 +10,14 @@ const { findUser } = require('~/models');
|
|||
const banCache = new Keyv({ store: keyvMongo, namespace: ViolationTypes.BAN, ttl: 0 });
|
||||
const message = 'Your account has been temporarily banned due to violations of our service.';
|
||||
|
||||
/** @returns {string} Cache key for ban lookups, prefixed for Redis or raw for MongoDB */
|
||||
const getBanCacheKey = (prefix, value, useRedis) => {
|
||||
if (!value) {
|
||||
return '';
|
||||
}
|
||||
return useRedis ? `ban_cache:${prefix}:${value}` : value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Respond to the request if the user is banned.
|
||||
*
|
||||
|
|
@ -63,25 +71,16 @@ const checkBan = async (req, res, next = () => {}) => {
|
|||
return next();
|
||||
}
|
||||
|
||||
let cachedIPBan;
|
||||
let cachedUserBan;
|
||||
const useRedis = isEnabled(process.env.USE_REDIS);
|
||||
const ipKey = getBanCacheKey('ip', req.ip, useRedis);
|
||||
const userKey = getBanCacheKey('user', userId, useRedis);
|
||||
|
||||
let ipKey = '';
|
||||
let userKey = '';
|
||||
const [cachedIPBan, cachedUserBan] = await Promise.all([
|
||||
ipKey ? banCache.get(ipKey) : undefined,
|
||||
userKey ? banCache.get(userKey) : undefined,
|
||||
]);
|
||||
|
||||
if (req.ip) {
|
||||
ipKey = isEnabled(process.env.USE_REDIS) ? `ban_cache:ip:${req.ip}` : req.ip;
|
||||
cachedIPBan = await banCache.get(ipKey);
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
userKey = isEnabled(process.env.USE_REDIS) ? `ban_cache:user:${userId}` : userId;
|
||||
cachedUserBan = await banCache.get(userKey);
|
||||
}
|
||||
|
||||
const cachedBan = cachedIPBan || cachedUserBan;
|
||||
|
||||
if (cachedBan) {
|
||||
if (cachedIPBan || cachedUserBan) {
|
||||
req.banned = true;
|
||||
return await banResponse(req, res);
|
||||
}
|
||||
|
|
@ -93,41 +92,47 @@ const checkBan = async (req, res, next = () => {}) => {
|
|||
return next();
|
||||
}
|
||||
|
||||
let ipBan;
|
||||
let userBan;
|
||||
const [ipBan, userBan] = await Promise.all([
|
||||
req.ip ? banLogs.get(req.ip) : undefined,
|
||||
userId ? banLogs.get(userId) : undefined,
|
||||
]);
|
||||
|
||||
if (req.ip) {
|
||||
ipBan = await banLogs.get(req.ip);
|
||||
}
|
||||
const banData = ipBan || userBan;
|
||||
|
||||
if (userId) {
|
||||
userBan = await banLogs.get(userId);
|
||||
}
|
||||
|
||||
const isBanned = !!(ipBan || userBan);
|
||||
|
||||
if (!isBanned) {
|
||||
if (!banData) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const timeLeft = Number(isBanned.expiresAt) - Date.now();
|
||||
|
||||
if (timeLeft <= 0 && ipKey) {
|
||||
await banLogs.delete(ipKey);
|
||||
const expiresAt = Number(banData.expiresAt);
|
||||
if (!banData.expiresAt || isNaN(expiresAt)) {
|
||||
req.banned = true;
|
||||
return await banResponse(req, res);
|
||||
}
|
||||
|
||||
if (timeLeft <= 0 && userKey) {
|
||||
await banLogs.delete(userKey);
|
||||
const timeLeft = expiresAt - Date.now();
|
||||
|
||||
if (timeLeft <= 0) {
|
||||
const cleanups = [];
|
||||
if (ipBan) {
|
||||
cleanups.push(banLogs.delete(req.ip));
|
||||
}
|
||||
if (userBan) {
|
||||
cleanups.push(banLogs.delete(userId));
|
||||
}
|
||||
await Promise.all(cleanups);
|
||||
return next();
|
||||
}
|
||||
|
||||
const cacheWrites = [];
|
||||
if (ipKey) {
|
||||
banCache.set(ipKey, isBanned, timeLeft);
|
||||
cacheWrites.push(banCache.set(ipKey, banData, timeLeft));
|
||||
}
|
||||
|
||||
if (userKey) {
|
||||
banCache.set(userKey, isBanned, timeLeft);
|
||||
cacheWrites.push(banCache.set(userKey, banData, timeLeft));
|
||||
}
|
||||
await Promise.all(cacheWrites).catch((err) =>
|
||||
logger.warn('[checkBan] Failed to write ban cache:', err),
|
||||
);
|
||||
|
||||
req.banned = true;
|
||||
return await banResponse(req, res);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue