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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧊 fix: Fence Auth User Cache Writes After Eviction and Evict Favorite Holders (#17505)
Marco Beretta7f597b478728
diff --git a/api/strategies/openIdJwtStrategy.js b/api/strategies/openIdJwtStrategy.jsindex eb584176bd..a0e1dcdfb7 100644--- a/api/strategies/openIdJwtStrategy.js+++ b/api/strategies/openIdJwtStrategy.js@@ -17,6 +17,7 @@ const {getValidOpenIdReuseUserId,invalidateCachedAuthUserDoc,setCachedAuthUserDoc,+ timeAuthUserLookup,getHttpsProxyAgent,isAccessTokenJwt,math,@@ -186,16 +187,18 @@ const openIdJwtLogin = (openIdConfig) => {authUserCacheMode === 'on' &&cachedUser &&isUserInAuthCacheScope(cachedUser, authUserCacheScope);- const lookupResult = servedCachedUser- ? { user: cachedUser, error: null, migration: false }- : await findOpenIDUser({- findUser,- email: payload ? getOpenIdEmail(payload) : undefined,- openidId: payload?.sub,- openidIssuer,- idOnTheSource: payload?.oid,- strategyName: 'openIdJwtLogin',- });+ const { result: lookupResult, lookupStartedAt } = servedCachedUser+ ? { result: { user: cachedUser, error: null, migration: false } }+ : await timeAuthUserLookup(() =>+ findOpenIDUser({+ findUser,+ email: payload ? getOpenIdEmail(payload) : undefined,+ openidId: payload?.sub,+ openidIssuer,+ idOnTheSource: payload?.oid,+ strategyName: 'openIdJwtLogin',+ }),+ );const { user, error, migration } = lookupResult;if (error) {@@ -247,7 +250,12 @@ const openIdJwtLogin = (openIdConfig) => {cacheKey: authUserCacheKey,});} else if (!servedCachedUser && isUserInAuthCacheScope(user, authUserCacheScope)) {- await setCachedAuthUserDoc(authUserCacheStore, authUserCacheKey, user);+ await setCachedAuthUserDoc(+ authUserCacheStore,+ authUserCacheKey,+ user,+ lookupStartedAt,+ );}}diff --git a/api/strategies/openIdJwtStrategy.spec.js b/api/strategies/openIdJwtStrategy.spec.jsindex 6615e39eee..8602e822ac 100644--- a/api/strategies/openIdJwtStrategy.spec.js+++ b/api/strategies/openIdJwtStrategy.spec.js@@ -46,6 +46,7 @@ jest.mock('@librechat/api', () => ({getValidOpenIdReuseUserId: jest.fn(),invalidateCachedAuthUserDoc: jest.fn(),setCachedAuthUserDoc: jest.fn(),+ timeAuthUserLookup: jest.requireActual('@librechat/api').timeAuthUserLookup,getHttpsProxyAgent: jest.fn(() => undefined),isAccessTokenJwt: jest.requireActual('@librechat/api').isAccessTokenJwt,math: jest.fn((val, fallback) => fallback),@@ -663,7 +664,11 @@ describe('openIdJwtStrategy – auth user document cache', () => {it('populates the cache after a miss with the fresh user document', async () => {getAuthUserDocCacheMode.mockReturnValue('on');getCachedAuthUserDoc.mockResolvedValue(undefined);- findOpenIDUser.mockResolvedValue({ user: { ...baseUser }, error: null, migration: false });+ let lookupAt;+ findOpenIDUser.mockImplementation(async () => {+ lookupAt = Date.now();+ return { user: { ...baseUser }, error: null, migration: false };+ });await invokeVerify(req, payload);@@ -672,7 +677,10 @@ describe('openIdJwtStrategy – auth user document cache', () => {mockAuthUserDocCacheStore,'auth-user-doc-key',expect.objectContaining({ id: 'user-abc' }),+ expect.any(Number),);+ /** The write is stamped with when the lookup began, so a slow lookup is not cached. */+ expect(setCachedAuthUserDoc.mock.calls[0][3]).toBeLessThanOrEqual(lookupAt);expect(invalidateCachedAuthUserDoc).not.toHaveBeenCalled();});@@ -706,6 +714,7 @@ describe('openIdJwtStrategy – auth user document cache', () => {mockAuthUserDocCacheStore,'auth-user-doc-key',expect.objectContaining({ id: 'tenant-b-user', tenantId: 'tenant-b' }),+ expect.any(Number),);});diff --git a/e2e/specs/mock/scenarios/delete-user-cli.spec.ts b/e2e/specs/mock/scenarios/delete-user-cli.spec.tsindex 9282f5b86c..571ab45e24 100644--- a/e2e/specs/mock/scenarios/delete-user-cli.spec.ts+++ b/e2e/specs/mock/scenarios/delete-user-cli.spec.ts@@ -1,7 +1,14 @@import fs from 'fs';import path from 'path';+import { Keyv } from 'keyv';import { ObjectId } from 'mongodb';+import KeyvRedis from '@keyv/redis';import { expect, test } from '@playwright/test';+import {+ CacheKeys,+ AUTH_USER_DOC_BY_ID_PREFIX,+ AUTH_USER_DOC_EVICTED_PREFIX,+} from 'librechat-data-provider';import { spawn } from 'node:child_process';import { randomInt, randomUUID } from 'node:crypto';import type { APIRequestContext } from '@playwright/test';@@ -138,11 +145,13 @@ const KEPT = {function runDeleteCli(email: string,deleteTransactions: boolean,+ extraEnv: NodeJS.ProcessEnv = {},): Promise<{ code: number | null; stdout: string; stderr: string }> {const child = spawn(process.execPath, [path.join(REPO_ROOT, 'config/delete-user.js'), email], {cwd: REPO_ROOT,env: {...process.env,+ ...extraEnv,MONGO_URI: getMongoUri(),/** The harness server already built the indexes; skip the module-scope rebuild. */NODE_OPTIONS: process.env.NODE_OPTIONS@@ -222,6 +231,85 @@ test.describe('account erasure', () => {});}+ test('deleting a user evicts the cached auth state of everyone who favorited their agents @scenario:cli-delete-user-evicts-favorite-holders', async ({+ playwright,+ baseURL,+ }) => {+ test.skip(process.env.E2E_STREAM_STORE !== 'redis', 'Runs in the Redis integration lane');+ test.setTimeout(150_000);+ const request = await playwright.request.newContext({ baseURL });+ const redisUri = process.env.REDIS_URI ?? 'redis://127.0.0.1:6379';+ const prefix = `cli-favorites-${randomUUID()}`;+ const adapter = new KeyvRedis(redisUri, { throwOnErrors: true, connectionTimeout: 5000 });+ // Match standardCache's namespace layering without initializing app singletons in this worker.+ const cache = new Keyv(adapter, { namespace: CacheKeys.AUTH_USER_DOC });+ adapter.namespace = prefix;+ adapter.keyPrefixSeparator = '::';+ const keys: string[] = [];+ try {+ const ownerEmail = await register(request, 'cli-agent-owner');+ const holderEmail = await register(request, 'cli-agent-holder');+ const bystanderEmail = await register(request, 'cli-agent-bystander');+ const agentId = `agent_${randomUUID()}`;+ const [holderId, bystanderId] = await withMongo(async (db) => {+ const users = db.collection('users');+ const owner = await users.findOne({ email: ownerEmail });+ await db.collection('agents').insertOne({+ id: agentId,+ name: 'Favorited agent',+ provider: 'openAI',+ model: 'gpt-4o-mini',+ author: owner!._id,+ });+ await users.updateOne({ email: holderEmail }, { $set: { favorites: [{ agentId }] } });+ const holder = await users.findOne({ email: holderEmail });+ const bystander = await users.findOne({ email: bystanderEmail });+ return [holder!._id.toString(), bystander!._id.toString()];+ });+ /** Each user has a cached auth document named by their reverse index. */+ for (const userId of [holderId, bystanderId]) {+ const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`;+ const docKey = `auth-user-doc:${userId}`;+ keys.push(indexKey, docKey, `${AUTH_USER_DOC_EVICTED_PREFIX}:${userId}`);+ await cache.set(indexKey, [docKey], 120_000);+ await cache.set(+ docKey,+ { version: 2, cachedAt: Date.now(), user: { _id: userId, favorites: [{ agentId }] } },+ 120_000,+ );+ }++ const result = await runDeleteCli(ownerEmail, true, {+ USE_REDIS: 'true',+ USE_REDIS_CLUSTER: 'false',+ REDIS_URI: redisUri,+ REDIS_KEY_PREFIX: prefix,+ REDIS_KEY_PREFIX_VAR: '',+ AUTH_USER_CACHE_MODE: 'on',+ FORCED_IN_MEMORY_CACHE_NAMESPACES: '',+ });+ expect(result.code, result.stderr.slice(-800)).toBe(0);+ expect(result.stdout).toContain('Successfully deleted user');++ await withMongo(async (db) => {+ expect(await db.collection('agents').countDocuments({ id: agentId })).toBe(0);+ const holder = await db.collection('users').findOne({ email: holderEmail });+ expect(holder?.favorites).toEqual([]);+ });+ expect(await cache.get(`auth-user-doc:${holderId}`)).toBeUndefined();+ expect(await cache.get(`${AUTH_USER_DOC_EVICTED_PREFIX}:${holderId}`)).toBeDefined();+ expect(await cache.get(`auth-user-doc:${bystanderId}`)).toBeDefined();+ expect(await cache.get(`${AUTH_USER_DOC_EVICTED_PREFIX}:${bystanderId}`)).toBeUndefined();+ } finally {+ try {+ await Promise.all(keys.map((key) => cache.delete(key)));+ } finally {+ await cache.disconnect();+ await request.dispose();+ }+ }+ });+test('self-service deletion erases the same stores as the CLI @scenario:self-delete-erases-owned-data', async ({playwright,baseURL,diff --git a/e2e/specs/mock/scenarios/reset-password.spec.ts b/e2e/specs/mock/scenarios/reset-password.spec.tsindex a25739132a..a310b59500 100644--- a/e2e/specs/mock/scenarios/reset-password.spec.ts+++ b/e2e/specs/mock/scenarios/reset-password.spec.ts@@ -4,10 +4,14 @@ import os from 'os';import { Keyv } from 'keyv';import KeyvRedis from '@keyv/redis';import { expect, test } from '@playwright/test';+import { isAuthUserDocEvictionFenced } from '@librechat/data-schemas';import {CacheKeys,AUTH_USER_DOC_BY_ID_PREFIX,AUTH_USER_DOC_CACHE_TTL_MS,+ AUTH_USER_DOC_MAX_AGE_MS,+ AUTH_USER_DOC_EVICTED_PREFIX,+ AUTH_USER_DOC_EVICTION_FENCE_TTL_MS,} from 'librechat-data-provider';import { spawn } from 'node:child_process';import { randomInt, randomUUID } from 'node:crypto';@@ -251,6 +255,87 @@ test.describe('CLI password reset', () => {});}+ test('hides pre-reset documents the eviction could not name @scenario:cli-reset-fences-stale-cache-writes', async ({+ playwright,+ baseURL,+ }) => {+ test.setTimeout(90_000);+ const request = await playwright.request.newContext({+ baseURL,+ extraHTTPHeaders: {+ 'X-Forwarded-For': `127.${randomInt(1, 255)}.${randomInt(1, 255)}.${randomInt(1, 255)}`,+ },+ });+ const email = `cli-fence-${randomUUID().slice(0, 8)}@example.com`;+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lc-reset-'));+ const redisUri = process.env.REDIS_URI ?? 'redis://127.0.0.1:6379';+ const prefix = `cli-fence-${randomUUID()}`;+ const adapter = new KeyvRedis(redisUri, { throwOnErrors: true, connectionTimeout: 5000 });+ const cache = new Keyv(adapter, { namespace: CacheKeys.AUTH_USER_DOC });+ adapter.namespace = prefix;+ adapter.keyPrefixSeparator = '::';+ const keys: string[] = [];+ try {+ const register = await request.post('/api/auth/register', {+ data: { email, name: 'CLI Fence', password: PASSWORD, confirm_password: PASSWORD },+ });+ expect(register.ok()).toBeTruthy();+ const login = await request.post('/api/auth/login', { data: { email, password: PASSWORD } });+ expect(login.ok()).toBeTruthy();+ const { user } = (await login.json()) as { user: { _id: string } };+ const otherUserId = randomUUID();+ const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${user._id}`;+ const fenceKey = `${AUTH_USER_DOC_EVICTED_PREFIX}:${user._id}`;+ /** Indexed, so the eviction deletes it; and one a concurrent index write dropped. */+ const indexedKey = 'auth-user-doc:indexed';+ const unindexedKey = 'auth-user-doc:unindexed';+ const stale = { version: 2, cachedAt: Date.now(), user: { _id: user._id, id: user._id } };+ keys.push(indexKey, fenceKey, indexedKey, unindexedKey);+ await cache.set(indexKey, [indexedKey], 120_000);+ await cache.set(indexedKey, stale, 120_000);+ await cache.set(unindexedKey, stale, 120_000);++ const cli = await runResetCli(email, cwd, {+ ...process.env,+ USE_REDIS: 'true',+ USE_REDIS_CLUSTER: 'false',+ REDIS_URI: redisUri,+ REDIS_KEY_PREFIX: prefix,+ REDIS_KEY_PREFIX_VAR: '',+ AUTH_USER_CACHE_MODE: 'on',+ FORCED_IN_MEMORY_CACHE_NAMESPACES: '',+ });+ expect(cli.code, cli.stderr.slice(-400)).toBe(0);+ expect(cli.stdout).toContain('Password successfully reset!');+ /** The fence proves the eviction, so the CLI no longer waits out the cache TTL. */+ expect(cli.reportDelayMs).toBeLessThan(AUTH_USER_DOC_CACHE_TTL_MS);++ /** A document written after the eviction by a request that read the user before it. */+ const lateKey = 'auth-user-doc:late';+ keys.push(lateKey);+ await cache.set(lateKey, stale, 120_000);++ expect(await cache.get(indexedKey)).toBeUndefined();+ expect(await cache.get(unindexedKey)).toEqual(stale);+ expect(await isAuthUserDocEvictionFenced(cache, user._id)).toBe(true);+ expect(await isAuthUserDocEvictionFenced(cache, otherUserId)).toBe(false);+ const client = await adapter.getClient();+ const fenceTtl = await client.pTTL(`${prefix}::${CacheKeys.AUTH_USER_DOC}:${fenceKey}`);+ /** Still standing once a document cached before the reset has expired. */+ expect(fenceTtl).toBeGreaterThan(AUTH_USER_DOC_CACHE_TTL_MS);+ expect(fenceTtl).toBeLessThanOrEqual(AUTH_USER_DOC_EVICTION_FENCE_TTL_MS);+ } finally {+ try {+ await Promise.all(keys.map((key) => cache.delete(key)));+ } finally {+ await cache.disconnect();+ await request.dispose();+ fs.rmSync(cwd, { recursive: true, force: true });+ await deleteUserByEmail(email);+ }+ }+ });+test('reports the reset only after unevictable cached credentials expire @scenario:cli-reset-outlasts-failed-cache-eviction', async ({playwright,baseURL,@@ -304,7 +389,7 @@ test.describe('CLI password reset', () => {const cli = await runResetCli(email, cwd, env);expect(cli.code, cli.stderr.slice(-400)).toBe(0);expect(cli.stdout).toContain('Password successfully reset!');- expect(cli.reportDelayMs).toBeGreaterThanOrEqual(AUTH_USER_DOC_CACHE_TTL_MS);+ expect(cli.reportDelayMs).toBeGreaterThanOrEqual(AUTH_USER_DOC_MAX_AGE_MS);expect(await cache.get(controlKey)).toEqual({ credentialsChangedAt: null });await withMongo(async (db) => {const resetUser = await db.collection('users').findOne({ email });diff --git a/packages/api/src/auth/credentials.eviction.spec.ts b/packages/api/src/auth/credentials.eviction.spec.tsindex 3c574b369d..acc9f68e3d 100644--- a/packages/api/src/auth/credentials.eviction.spec.ts+++ b/packages/api/src/auth/credentials.eviction.spec.ts@@ -2,13 +2,16 @@ import { Keyv } from 'keyv';import mongoose from 'mongoose';import { MongoMemoryServer } from 'mongodb-memory-server';import { createMethods, createModels } from '@librechat/data-schemas';-import { AUTH_USER_DOC_BY_ID_PREFIX, CacheKeys } from 'librechat-data-provider';+import {+ CacheKeys,+ AUTH_USER_DOC_MAX_AGE_MS,+ AUTH_USER_DOC_BY_ID_PREFIX,+} from 'librechat-data-provider';import type { IUser } from '@librechat/data-schemas';import {getCachedAuthUserDoc,setCachedAuthUserDoc,buildAuthUserDocCacheKey,- AUTH_USER_DOC_CACHE_TTL_MS,} from './userDocCache';import { isTokenRetired } from './twoFactor';@@ -63,7 +66,7 @@ describe('credential change with a failing auth cache', () => {if (!cacheKey) {throw new Error('expected a cache key');}- await setCachedAuthUserDoc(store, cacheKey, user);+ await setCachedAuthUserDoc(store, cacheKey, user, Date.now());const oldToken = { issuedAt: Math.floor(Date.now() / 1000) - 60 };expect(isTokenRetired(oldToken, await getCachedAuthUserDoc(store, cacheKey))).toBe(false);@@ -74,7 +77,7 @@ describe('credential change with a failing auth cache', () => {const startedAt = Date.now();await methods.awaitAuthUserDocEviction(userId);- expect(Date.now() - startedAt).toBeGreaterThanOrEqual(AUTH_USER_DOC_CACHE_TTL_MS);+ expect(Date.now() - startedAt).toBeGreaterThanOrEqual(AUTH_USER_DOC_MAX_AGE_MS);expect(updated?.credentialsChangedAt).toBeInstanceOf(Date);await expect(getCachedAuthUserDoc(store, cacheKey)).resolves.toBeUndefined();const current = await methods.findUser({ openidId: 'subject-1' });diff --git a/packages/api/src/auth/userDocCache.spec.ts b/packages/api/src/auth/userDocCache.spec.tsindex 766e33a4d9..011f07b4a6 100644--- a/packages/api/src/auth/userDocCache.spec.ts+++ b/packages/api/src/auth/userDocCache.spec.ts@@ -1,6 +1,6 @@import { Types } from 'mongoose';-import { logger } from '@librechat/data-schemas';import { CacheKeys } from 'librechat-data-provider';+import { logger, buildAuthUserDocEvictionFenceKey } from '@librechat/data-schemas';import {AUTH_USER_DOC_CACHE_TTL_MS,buildAuthUserDocCacheKey,@@ -9,6 +9,7 @@ import {getCachedAuthUserDoc,invalidateCachedAuthUserDoc,setCachedAuthUserDoc,+ timeAuthUserLookup,} from './userDocCache';import { cacheConfig } from '~/cache/cacheConfig';@@ -152,18 +153,23 @@ describe('auth user document cache helpers', () => {const cacheKey = 'auth-user-doc:v2:key';const userId = new Types.ObjectId();- await setCachedAuthUserDoc(store, cacheKey, {- _id: userId,- id: userId.toString(),- email: '[email protected]',- provider: 'openid',- password: 'secret',- refreshToken: [{ refreshToken: 'secret' }],- federatedTokens: { access_token: 'secret' },- openidTokens: { access_token: 'secret' },- totpSecret: 'secret',- backupCodes: [{ codeHash: 'secret', used: false }],- });+ await setCachedAuthUserDoc(+ store,+ cacheKey,+ {+ _id: userId,+ id: userId.toString(),+ email: '[email protected]',+ provider: 'openid',+ password: 'secret',+ refreshToken: [{ refreshToken: 'secret' }],+ federatedTokens: { access_token: 'secret' },+ openidTokens: { access_token: 'secret' },+ totpSecret: 'secret',+ backupCodes: [{ codeHash: 'secret', used: false }],+ },+ Date.now(),+ );const cached = store.values.get(cacheKey) as { user: Record<string, unknown> };expect(cached.user).toMatchObject({@@ -205,10 +211,15 @@ describe('auth user document cache helpers', () => {return true;});- await setCachedAuthUserDoc(store, 'auth-user-doc:v2:orphan', {- _id: userId,- email: '[email protected]',- });+ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc:v2:orphan',+ {+ _id: userId,+ email: '[email protected]',+ },+ Date.now(),+ );expect(store.values.has('auth-user-doc:v2:orphan')).toBe(false);expect(logger.warn).toHaveBeenCalledWith('[authUserDocCache] Cache write failed', {@@ -226,14 +237,24 @@ describe('auth user document cache helpers', () => {Array.from({ length: 20 }, (_value, index) => `existing-key-${index}`),);- await setCachedAuthUserDoc(store, 'existing-key-10', {- _id: objectId,- email: '[email protected]',- });- await setCachedAuthUserDoc(store, 'new-key', {- _id: objectId,- email: '[email protected]',- });+ await setCachedAuthUserDoc(+ store,+ 'existing-key-10',+ {+ _id: objectId,+ email: '[email protected]',+ },+ Date.now(),+ );+ await setCachedAuthUserDoc(+ store,+ 'new-key',+ {+ _id: objectId,+ email: '[email protected]',+ },+ Date.now(),+ );const indexed = store.values.get(indexKey);expect(indexed).toHaveLength(20);@@ -244,7 +265,12 @@ describe('auth user document cache helpers', () => {it('returns cached user documents only for the current cache version', async () => {const store = makeStore();- store.values.set('current', { version: 2, cachedAt: Date.now(), user: { id: 'user-1' } });+ store.values.set('current', {+ version: 2,+ cachedAt: Date.now(),+ expiresAt: Date.now() + AUTH_USER_DOC_CACHE_TTL_MS,+ user: { id: 'user-1' },+ });store.values.set('stale', { version: 1, cachedAt: Date.now(), user: { id: 'user-2' } });await expect(getCachedAuthUserDoc(store, 'current')).resolves.toEqual({ id: 'user-1' });@@ -263,6 +289,200 @@ describe('auth user document cache helpers', () => {expect(store.delete).toHaveBeenCalledWith('key-c');});+ it('does not serve a document read before an eviction and written after it', async () => {+ const store = makeStore();+ const userId = new Types.ObjectId();+ const lookupStartedAt = Date.now();++ await invalidateCachedAuthUserDoc(store, { userId: userId.toString() });+ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc:v2:late',+ { _id: userId, email: '[email protected]' },+ lookupStartedAt,+ );++ expect(store.values.has('auth-user-doc:v2:late')).toBe(true);+ await expect(getCachedAuthUserDoc(store, 'auth-user-doc:v2:late')).resolves.toBeUndefined();+ });++ it('hides a cached document the reverse index lost once the user is evicted', async () => {+ const store = makeStore();+ const userId = new Types.ObjectId();+ const user = { _id: userId, email: '[email protected]' };+ await setCachedAuthUserDoc(store, 'auth-user-doc:v2:lost', user, Date.now());+ await setCachedAuthUserDoc(store, 'auth-user-doc:v2:kept', user, Date.now());+ /** A concurrent read-modify-write of the index dropped the first key. */+ store.values.set(buildAuthUserDocReverseIndexKey(userId.toString()), ['auth-user-doc:v2:kept']);++ await invalidateCachedAuthUserDoc(store, { userId: userId.toString() });++ expect(store.values.has('auth-user-doc:v2:lost')).toBe(true);+ expect(store.values.has('auth-user-doc:v2:kept')).toBe(false);+ await expect(getCachedAuthUserDoc(store, 'auth-user-doc:v2:lost')).resolves.toBeUndefined();+ });++ it('serves a document again once the eviction fence expires', async () => {+ const store = makeStore();+ const userId = new Types.ObjectId();+ await invalidateCachedAuthUserDoc(store, { userId: userId.toString() });+ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc:v2:fresh',+ { _id: userId, email: '[email protected]' },+ Date.now(),+ );+ await expect(getCachedAuthUserDoc(store, 'auth-user-doc:v2:fresh')).resolves.toBeUndefined();++ store.values.delete(buildAuthUserDocEvictionFenceKey(userId.toString()));++ await expect(getCachedAuthUserDoc(store, 'auth-user-doc:v2:fresh')).resolves.toMatchObject({+ email: '[email protected]',+ });+ });++ it('does not cache a lookup slower than the cache TTL', async () => {+ const store = makeStore();+ const userId = new Types.ObjectId();++ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc:v2:slow',+ { _id: userId, email: '[email protected]' },+ Date.now() - AUTH_USER_DOC_CACHE_TTL_MS - 1,+ );++ expect(store.set).not.toHaveBeenCalled();+ });++ it('skips a cached document whose eviction fence cannot be read', async () => {+ const store = makeStore();+ const userId = new Types.ObjectId();+ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc:v2:key',+ { _id: userId, email: '[email protected]' },+ Date.now(),+ );+ const fenceKey = buildAuthUserDocEvictionFenceKey(userId.toString());+ const get = store.get;+ store.get = async <T = unknown>(key: string) => {+ if (key === fenceKey) {+ throw new Error('redis unavailable');+ }+ return get<T>(key);+ };++ await expect(getCachedAuthUserDoc(store, 'auth-user-doc:v2:key')).resolves.toBeUndefined();+ });++ describe('when the write stalls after the lookup', () => {+ let now: number;+ beforeEach(() => {+ now = 1_000_000;+ jest.spyOn(Date, 'now').mockImplementation(() => now);+ });+ afterEach(() => {+ jest.restoreAllMocks();+ });++ /** The index write stalls while an eviction lands, then the stale document is written. */+ function stallIndexWrite(store: ReturnType<typeof makeStore>, userId: string, stallMs: number) {+ const indexKey = buildAuthUserDocReverseIndexKey(userId);+ store.set.mockImplementation(async (key: string, value: unknown) => {+ if (key === indexKey) {+ await invalidateCachedAuthUserDoc(store, { userId });+ now += stallMs;+ }+ store.values.set(key, value);+ return true;+ });+ }++ it('anchors the expiry of a late stale document to its lookup, not to the write', async () => {+ const store = makeStore();+ const userId = new Types.ObjectId();+ const lookupStartedAt = now;+ now += 4_000;+ stallIndexWrite(store, userId.toString(), 5_500);++ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc:v2:stalled',+ { _id: userId, email: '[email protected]' },+ lookupStartedAt,+ );++ const ttl = store.set.mock.calls.find(([key]) => key === 'auth-user-doc:v2:stalled')?.[2];+ expect(ttl).toBe(lookupStartedAt + AUTH_USER_DOC_CACHE_TTL_MS * 2 - now);+ await expect(+ getCachedAuthUserDoc(store, 'auth-user-doc:v2:stalled'),+ ).resolves.toBeUndefined();++ /** Even with the eviction fence gone and the entry somehow kept, it is past its expiry. */+ store.values.delete(buildAuthUserDocEvictionFenceKey(userId.toString()));+ now = lookupStartedAt + AUTH_USER_DOC_CACHE_TTL_MS * 2 + 1;+ await expect(+ getCachedAuthUserDoc(store, 'auth-user-doc:v2:stalled'),+ ).resolves.toBeUndefined();+ });++ it('does not serve a document that expired while its fence read stalled', async () => {+ const store = makeStore();+ const userId = new Types.ObjectId();+ const lookupStartedAt = now;+ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc:v2:unindexed',+ { _id: userId, email: '[email protected]' },+ lookupStartedAt,+ );+ const fenceKey = buildAuthUserDocEvictionFenceKey(userId.toString());+ const get = store.get;+ /** The fence GET returns only after the fence and the document have both expired. */+ store.get = async <T = unknown>(key: string) => {+ if (key === fenceKey) {+ now = lookupStartedAt + AUTH_USER_DOC_CACHE_TTL_MS * 3 + 1;+ return undefined as T | undefined;+ }+ return get<T>(key);+ };++ await expect(+ getCachedAuthUserDoc(store, 'auth-user-doc:v2:unindexed'),+ ).resolves.toBeUndefined();+ });++ it('does not write a document whose lookup is two TTLs old once the index write returns', async () => {+ const store = makeStore();+ const userId = new Types.ObjectId();+ const lookupStartedAt = now;+ stallIndexWrite(store, userId.toString(), AUTH_USER_DOC_CACHE_TTL_MS * 2);++ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc:v2:expired',+ { _id: userId, email: '[email protected]' },+ lookupStartedAt,+ );++ expect(store.values.has('auth-user-doc:v2:expired')).toBe(false);+ });+ });++ it('stamps a lookup with the time before it ran', async () => {+ let ranAt = 0;+ const before = Date.now();+ const { result, lookupStartedAt } = await timeAuthUserLookup(async () => {+ ranAt = Date.now();+ return { user: 'found' };+ });++ expect(result).toEqual({ user: 'found' });+ expect(lookupStartedAt).toBeGreaterThanOrEqual(before);+ expect(lookupStartedAt).toBeLessThanOrEqual(ranAt);+ });+it('logs cache failures without throwing', async () => {const store = {get: async <T = unknown>(): Promise<T | undefined> => {diff --git a/packages/api/src/auth/userDocCache.ts b/packages/api/src/auth/userDocCache.tsindex c25fe0238e..87b1ee5c0d 100644--- a/packages/api/src/auth/userDocCache.ts+++ b/packages/api/src/auth/userDocCache.ts@@ -1,7 +1,8 @@import { createHash } from 'crypto';-import { logger, evictAuthUserDocs } from '@librechat/data-schemas';+import { logger, evictAuthUserDocs, isAuthUserDocEvictionFenced } from '@librechat/data-schemas';import {CacheKeys,+ AUTH_USER_DOC_MAX_AGE_MS,AUTH_USER_DOC_BY_ID_PREFIX,AUTH_USER_DOC_CACHE_TTL_MS,} from 'librechat-data-provider';@@ -31,6 +32,8 @@ export interface AuthUserDocCacheKeyInput {interface CachedAuthUserDoc {version: number;cachedAt: number;+ /** Two cache TTLs after the lookup began; never served later, however late it was written. */+ expiresAt: number;user: CachedAuthUser;}@@ -157,7 +160,17 @@ export async function getCachedAuthUserDoc(if (!cached || cached.version !== AUTH_USER_DOC_CACHE_VERSION || !cached.user) {return undefined;}- return cached.user;+ const isExpired = () => typeof cached.expiresAt !== 'number' || Date.now() > cached.expiresAt;+ if (isExpired()) {+ return undefined;+ }+ /** A recent eviction means this document may predate the change it evicted. */+ const userId = getUserId(cached.user);+ if (!userId || (await isAuthUserDocEvictionFenced(store, userId))) {+ return undefined;+ }+ /** The fence read can stall past both the fence and this document's expiry. */+ return isExpired() ? undefined : cached.user;} catch (error) {logger.warn('[authUserDocCache] Cache read failed; falling back to user lookup', {error: error instanceof Error ? error.message : String(error),@@ -166,29 +179,57 @@ export async function getCachedAuthUserDoc(}}+/**+ * Runs the database lookup whose result a cache write may store, and stamps when it began:+ * `setCachedAuthUserDoc` anchors the document's lifetime to that moment.+ */+export async function timeAuthUserLookup<T>(+ lookup: () => Promise<T>,+): Promise<{ result: T; lookupStartedAt: number }> {+ const lookupStartedAt = Date.now();+ return { result: await lookup(), lookupStartedAt };+}+/*** The reverse index is written first and outlives every document it names, so eviction can- * always find a cached document: when the index write fails, the document is not cached.+ * usually find a cached document: when the index write fails, the document is not cached.+ * `lookupStartedAt` is when the database read of `user` began. A document's lifetime is anchored+ * to it rather than to the write: it expires, and is never served, two cache TTLs after the+ * lookup began, however long the writes took. An eviction's fence lasts three TTLs from a moment+ * after any lookup it can race, so it hides every document read before it, including one the+ * reverse index lost.*/export async function setCachedAuthUserDoc(store: AuthUserDocCacheStore,cacheKey: string,user: Partial<IUser>,+ lookupStartedAt: number,): Promise<void> {+ const expiresAt = lookupStartedAt + AUTH_USER_DOC_MAX_AGE_MS;+ if (Date.now() - lookupStartedAt > AUTH_USER_DOC_CACHE_TTL_MS) {+ return;+ }try {const sanitized = sanitizeUserForCache(user);const userId = getUserId(sanitized);if (userId) {await rememberUserCacheKey(store, userId, cacheKey, AUTH_USER_DOC_CACHE_TTL_MS * 2);}+ /** Measured after the index write, which can stall, so the entry still expires on time. */+ const now = Date.now();+ const ttl = Math.min(AUTH_USER_DOC_CACHE_TTL_MS, expiresAt - now);+ if (ttl <= 0) {+ return;+ }await store.set(cacheKey,{version: AUTH_USER_DOC_CACHE_VERSION,- cachedAt: Date.now(),+ cachedAt: now,+ expiresAt,user: sanitized,} satisfies CachedAuthUserDoc,- AUTH_USER_DOC_CACHE_TTL_MS,+ ttl,);} catch (error) {logger.warn('[authUserDocCache] Cache write failed', {diff --git a/packages/api/src/favorites/pinned.spec.ts b/packages/api/src/favorites/pinned.spec.tsindex c3a57e27f2..7400992458 100644--- a/packages/api/src/favorites/pinned.spec.ts+++ b/packages/api/src/favorites/pinned.spec.ts@@ -132,10 +132,15 @@ describe('createPinnedOrderHandlers', () => {it('invalidates cached auth user state after persisting a new order', async () => {const store = makeAuthUserDocCacheStore();- await setCachedAuthUserDoc(store, 'auth-user-doc-key', {- id: 'user-1',- pinnedOrder: ['convo:stale'],- });+ await setCachedAuthUserDoc(+ store,+ 'auth-user-doc-key',+ {+ id: 'user-1',+ pinnedOrder: ['convo:stale'],+ },+ Date.now(),+ );expect(await getCachedAuthUserDoc(store, 'auth-user-doc-key')).toEqual(expect.objectContaining({ pinnedOrder: ['convo:stale'] }),);diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 4be333ce10..d9c87e1444 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -5252,6 +5252,21 @@ export const AUTH_USER_DOC_BY_ID_PREFIX = 'auth-user-doc-byid';/** Lifetime of a cached auth user document, and so the longest a stale one can be served. */export const AUTH_USER_DOC_CACHE_TTL_MS = 5000;+/**+ * Longest a cached auth user document can live after its lookup began: the lookup may take one+ * cache TTL before the write, and the document lives at most one more.+ */+export const AUTH_USER_DOC_MAX_AGE_MS = AUTH_USER_DOC_CACHE_TTL_MS * 2;++/** Per-user marker an eviction leaves so a lookup that began before it cannot be cached or served. */+export const AUTH_USER_DOC_EVICTED_PREFIX = 'auth-user-doc-evicted';++/**+ * Lifetime of that marker. A document is only cached when its lookup took at most one cache TTL+ * and then lives one more, so any document read before an eviction expires within two TTLs of it.+ */+export const AUTH_USER_DOC_EVICTION_FENCE_TTL_MS = AUTH_USER_DOC_CACHE_TTL_MS * 3;+/*** Enum for violation types, used to identify, log, and cache violations.*/diff --git a/packages/data-schemas/src/methods/agent.eviction.spec.ts b/packages/data-schemas/src/methods/agent.eviction.spec.tsnew file mode 100644index 0000000000..6f97dc5c94--- /dev/null+++ b/packages/data-schemas/src/methods/agent.eviction.spec.ts@@ -0,0 +1,136 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { CacheKeys, AUTH_USER_DOC_BY_ID_PREFIX } from 'librechat-data-provider';+import type { CacheStore, IUser } from '~/types';+import { buildAuthUserDocEvictionFenceKey } from '~/utils/eviction';+import { createModels } from '~/models';+import { createMethods } from './index';++let mongoServer: MongoMemoryServer;+let methods: ReturnType<typeof createMethods>;+const values = new Map<string, unknown>();+const cache: CacheStore = {+ get: async (key) => values.get(key),+ set: async (key, value) => values.set(key, value),+ delete: async (key) => values.delete(key),+};+const originalMode = process.env.AUTH_USER_CACHE_MODE;++beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ await mongoose.connect(mongoServer.getUri());+ createModels(mongoose);+ methods = createMethods(mongoose, {+ getCache: (key) => (key === CacheKeys.AUTH_USER_DOC ? cache : undefined),+ });+});++afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+ if (originalMode === undefined) {+ delete process.env.AUTH_USER_CACHE_MODE;+ } else {+ process.env.AUTH_USER_CACHE_MODE = originalMode;+ }+});++beforeEach(async () => {+ process.env.AUTH_USER_CACHE_MODE = 'on';+ values.clear();+ await mongoose.connection.dropDatabase();+});++/** Seeds a cached auth document for the user, named by its reverse index. */+function cacheUser(user: IUser): string {+ const userId = String(user._id);+ const docKey = `auth-user-doc:v2:${userId}`;+ values.set(`${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`, [docKey]);+ values.set(docKey, { version: 2, user: { _id: userId, favorites: user.favorites } });+ return docKey;+}++function expectEvicted(user: IUser, docKey: string) {+ expect(values.has(docKey)).toBe(false);+ expect(values.has(buildAuthUserDocEvictionFenceKey(String(user._id)))).toBe(true);+}++function expectCached(user: IUser, docKey: string) {+ expect(values.has(docKey)).toBe(true);+ expect(values.has(buildAuthUserDocEvictionFenceKey(String(user._id)))).toBe(false);+}++async function createAgent(id: string, author: mongoose.Types.ObjectId) {+ return methods.createAgent({ id, name: id, provider: 'test', model: 'test-model', author });+}++async function createUser(email: string, agentIds: string[]): Promise<IUser> {+ const user = await mongoose.models.User.create({+ email,+ provider: 'local',+ favorites: agentIds.map((agentId) => ({ agentId })),+ });+ return user.toObject() as IUser;+}++describe('agent favorite cleanup evicts cached auth users', () => {+ it('evicts every user that favorited an agent when the agent is deleted', async () => {+ await createAgent('agent_deleted', new mongoose.Types.ObjectId());+ const holder = await createUser('[email protected]', ['agent_deleted']);+ const bystander = await createUser('[email protected]', ['agent_other']);+ const holderKey = cacheUser(holder);+ const bystanderKey = cacheUser(bystander);++ await methods.deleteAgent({ id: 'agent_deleted' });++ const stored = await mongoose.models.User.findById(holder._id).lean<IUser>();+ expect(stored?.favorites).toEqual([]);+ expectEvicted(holder, holderKey);+ expectCached(bystander, bystanderKey);+ });++ it("evicts the favorite holders of a deleted user's agents", async () => {+ const author = new mongoose.Types.ObjectId();+ await createAgent('agent_owned', author);+ const holder = await createUser('[email protected]', ['agent_owned']);+ const bystander = await createUser('[email protected]', []);+ const holderKey = cacheUser(holder);+ const bystanderKey = cacheUser(bystander);++ await methods.deleteUserAgents(author.toString());++ const stored = await mongoose.models.User.findById(holder._id).lean<IUser>();+ expect(stored?.favorites).toEqual([]);+ expectEvicted(holder, holderKey);+ expectCached(bystander, bystanderKey);+ });++ it('evicts the users an agent is removed from after losing access', async () => {+ const agent = await createAgent('agent_revoked', new mongoose.Types.ObjectId());+ const revoked = await createUser('[email protected]', ['agent_revoked']);+ const kept = await createUser('[email protected]', ['agent_revoked']);+ const revokedKey = cacheUser(revoked);+ const keptKey = cacheUser(kept);++ await methods.removeAgentFromUserFavorites(String(agent._id), [String(revoked._id)]);++ const stored = await mongoose.models.User.findById(revoked._id).lean<IUser>();+ expect(stored?.favorites).toEqual([]);+ expectEvicted(revoked, revokedKey);+ expectCached(kept, keptKey);+ });++ it('does not read favorite holders when the auth user cache is off', async () => {+ delete process.env.AUTH_USER_CACHE_MODE;+ await createAgent('agent_uncached', new mongoose.Types.ObjectId());+ const holder = await createUser('[email protected]', ['agent_uncached']);+ const holderKey = cacheUser(holder);+ const distinct = jest.spyOn(mongoose.models.User, 'distinct');++ await methods.deleteAgent({ id: 'agent_uncached' });++ expect(distinct).not.toHaveBeenCalled();+ distinct.mockRestore();+ expectCached(holder, holderKey);+ });+});diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.tsindex 63dbfdd304..1162ba0210 100644--- a/packages/data-schemas/src/methods/agent.ts+++ b/packages/data-schemas/src/methods/agent.ts@@ -11,7 +11,8 @@ import {} from 'librechat-data-provider';import type { FilterQuery, Model, PipelineStage, ProjectionType, Types } from 'mongoose';import type { AgentSortOption, AgentToolResources } from 'librechat-data-provider';-import type { IAgent, IAclEntry, IUser, ActionQuery } from '~/types';+import type { IAgent, IAclEntry, IUser, ActionQuery, CacheStore } from '~/types';+import { evictAuthUserDocsForUsers, isAuthUserDocCacheEnabled } from '~/utils/eviction';import { withCodeEnvironmentReferences } from './codeEnvironment';import { OWNER_ACL_PERMISSION_BIT_SUPERSETS } from './aclEntry';import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';@@ -669,6 +670,8 @@ export interface AgentDeps {) => Promise<Types.ObjectId[]>;/** Recognizes skill IDs supplied by an external, non-database registry. */isExternalSkillId?: (id: string) => boolean;+ /** Returns a cache store for the given key, so favorite cleanup can evict cached auth users. */+ getCache?: (key: string) => CacheStore | undefined;}/** Plain projection used to discover runnable agent graphs without exposing Mongoose. */@@ -1885,6 +1888,15 @@ export function createAgentMethods(return [...shared];}+ /** Users whose favorites match, read only when their cached auth documents need evicting. */+ async function findFavoriteHolders(filter: FilterQuery<unknown>): Promise<string[]> {+ if (!isAuthUserDocCacheEnabled()) {+ return [];+ }+ const ids = await (mongoose.models.User as Model<unknown>).distinct('_id', filter);+ return ids.map(String);+ }+/*** Deletes an agent based on the provided search parameter.*/@@ -1910,13 +1922,15 @@ export function createAgentMethods(logger.error('[deleteAgent] Error removing agent from handoff edges', error);}try {- await User.updateMany(- {- ...(deletedAgent.tenantId !== undefined ? { tenantId: deletedAgent.tenantId } : {}),- 'favorites.agentId': deletedAgent.id,- },- { $pull: { favorites: { agentId: deletedAgent.id } } },- );+ const favoritesFilter = {+ ...(deletedAgent.tenantId !== undefined ? { tenantId: deletedAgent.tenantId } : {}),+ 'favorites.agentId': deletedAgent.id,+ };+ const holders = await findFavoriteHolders(favoritesFilter);+ await User.updateMany(favoritesFilter, {+ $pull: { favorites: { agentId: deletedAgent.id } },+ });+ await evictAuthUserDocsForUsers(deps.getCache, holders);} catch (error) {logger.error('[deleteAgent] Error removing agent from user favorites', error);}@@ -1990,10 +2004,12 @@ export function createAgentMethods(/** Reference cleanup precedes the irreversible delete, so a failure keeps the agent discoverable for retry. */for (const [tenant, tenantAgentIds] of idsByTenant) {await removeAgentIdsFromEdges(Agent, tenantAgentIds, tenant);- await User.updateMany(- { tenantId: tenant, 'favorites.agentId': { $in: tenantAgentIds } },- { $pull: { favorites: { agentId: { $in: tenantAgentIds } } } },- );+ const favoritesFilter = { tenantId: tenant, 'favorites.agentId': { $in: tenantAgentIds } };+ const holders = await findFavoriteHolders(favoritesFilter);+ await User.updateMany(favoritesFilter, {+ $pull: { favorites: { agentId: { $in: tenantAgentIds } } },+ });+ await evictAuthUserDocsForUsers(deps.getCache, holders);}await Agent.deleteMany({ _id: { $in: agentObjectIds } });@@ -2759,6 +2775,7 @@ export function createAgentMethods(},{ $pull: { favorites: { agentId: agent.id } } },);+ await evictAuthUserDocsForUsers(deps.getCache, userIds);}return {diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.tsindex 4c907cc5b6..65db79867b 100644--- a/packages/data-schemas/src/methods/index.ts+++ b/packages/data-schemas/src/methods/index.ts@@ -514,6 +514,7 @@ export function createMethods(getUserPrincipals: userGroupMethods.getUserPrincipals,findAccessibleResources: aclEntryMethods.findAccessibleResources,isExternalSkillId: deps.isExternalSkillId,+ getCache: deps.getCache,};const agentMethods = createAgentMethods(mongoose, agentDeps);return {diff --git a/packages/data-schemas/src/methods/role.ts b/packages/data-schemas/src/methods/role.tsindex 80bded7f08..ab8b6678ac 100644--- a/packages/data-schemas/src/methods/role.ts+++ b/packages/data-schemas/src/methods/role.ts@@ -1,5 +1,4 @@import {- AUTH_USER_DOC_BY_ID_PREFIX,CacheKeys,SystemRoles,roleDefaults,@@ -10,6 +9,7 @@ import type { FilterQuery, Model } from 'mongoose';import type { CacheStore, IRole, IUser } from '~/types';import { scopedCacheKey, getTenantId, runAsSystem, SYSTEM_TENANT_ID } from '~/config/tenantContext';import { tenantPartitionFilter } from '~/models/plugins/tenantIsolation';+import { evictAuthUserDocsForUsers } from '~/utils/eviction';import { escapeRegExp } from '~/utils/string';import logger from '~/config/winston';@@ -20,10 +20,6 @@ function isSystemRoleName(name: string): boolean {return systemRoleValues.has(name.toUpperCase());}-function isAuthUserDocCacheEnabled(): boolean {- return process.env.AUTH_USER_CACHE_MODE === 'on';-}-export class RoleConflictError extends Error {constructor(message: string) {super(message);@@ -670,30 +666,7 @@ export function createRoleMethods(}async function invalidateAuthUserDocCache(userIds: string[]): Promise<void> {- if (!isAuthUserDocCacheEnabled() || userIds.length === 0) {- return;- }- const cache = deps.getCache?.(CacheKeys.AUTH_USER_DOC);- if (!cache?.get || !cache?.delete) {- return;- }- try {- const uniqueUserIds = [...new Set(userIds.map((userId) => userId.toString()))];- await Promise.all(- uniqueUserIds.map(async (userId) => {- const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`;- const cachedKeys = await cache.get(indexKey);- if (Array.isArray(cachedKeys)) {- await Promise.all(- cachedKeys.map((key) => (typeof key === 'string' ? cache.delete?.(key) : undefined)),- );- }- await cache.delete?.(indexKey);- }),- );- } catch (cacheError) {- logger.error('[roleMethods] auth user doc cache invalidation failed:', cacheError);- }+ await evictAuthUserDocsForUsers(deps.getCache, userIds);}/** The users holding `roleName` in the caller's tenant partition, a page at a time. */diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.tsindex 4723760e22..d86d27e728 100644--- a/packages/data-schemas/src/methods/user.methods.spec.ts+++ b/packages/data-schemas/src/methods/user.methods.spec.ts@@ -3,7 +3,7 @@ import { MongoMemoryServer } from 'mongodb-memory-server';import {CacheKeys,AUTH_USER_DOC_BY_ID_PREFIX,- AUTH_USER_DOC_CACHE_TTL_MS,+ AUTH_USER_DOC_MAX_AGE_MS,} from 'librechat-data-provider';import type * as t from '~/types';import { createToolApprovalGrantModel } from '~/models/toolApprovalGrant';@@ -648,6 +648,7 @@ describe('User Methods - Database Tests', () => {});const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${user._id?.toString()}`;const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn().mockResolvedValue(['auth-cache-key-a', 'auth-cache-key-b']),delete: jest.fn().mockResolvedValue(true),};@@ -716,7 +717,7 @@ describe('User Methods - Database Tests', () => {await methodsWithCache.awaitAuthUserDocEviction(userId);expect(delay).toHaveBeenCalledTimes(1);- expect(delay.mock.calls[0][0]).toBeGreaterThan(AUTH_USER_DOC_CACHE_TTL_MS);+ expect(delay.mock.calls[0][0]).toBeGreaterThan(AUTH_USER_DOC_MAX_AGE_MS);expect(cache.delete).not.toHaveBeenCalledWith(`${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`);if (!failing.indexRead) {expect(cache.delete).toHaveBeenCalledWith('auth-cache-key-b');@@ -787,6 +788,7 @@ describe('User Methods - Database Tests', () => {});const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${user._id?.toString()}`;const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn().mockResolvedValue(['auth-cache-key-a']),delete: jest.fn().mockResolvedValue(true),};@@ -902,6 +904,7 @@ describe('User Methods - Database Tests', () => {const userId = user._id?.toString() ?? '';const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`;const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn().mockResolvedValue(['auth-cache-key']),delete: jest.fn().mockResolvedValue(true),};@@ -924,6 +927,7 @@ describe('User Methods - Database Tests', () => {samlId: 'original-saml-id',});const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn(),delete: jest.fn(),};@@ -1212,6 +1216,7 @@ describe('User Methods - Database Tests', () => {enableAuthUserDocCache();const { id, pendingBackupCodes } = await createEnrollingUser('[email protected]');const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn().mockResolvedValue(['cached-auth-document']),delete: jest.fn().mockResolvedValue(true),};@@ -1233,6 +1238,7 @@ describe('User Methods - Database Tests', () => {enableAuthUserDocCache();const { id } = await createEnrollingUser('[email protected]');const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn().mockResolvedValue(['cached-auth-document']),delete: jest.fn().mockResolvedValue(true),};@@ -1316,7 +1322,29 @@ describe('User Methods - Database Tests', () => {expect(stored?.termsAcceptedAt).toBeNull();expect(stored?.termsAcceptedSource).toBeUndefined();expect(cache.delete).toHaveBeenCalledWith('cached-accepted');- expect(delay).toHaveBeenCalledTimes(1);+ expect(delay).not.toHaveBeenCalled();+ });++ it('waits for cached auth documents to expire when an eviction fails', async () => {+ enableAuthUserDocCache();+ await User.create({+ name: 'Unevictable',+ email: '[email protected]',+ provider: 'local',+ termsAccepted: true,+ termsAcceptedAt: new Date(),+ });+ const cache = {+ get: jest.fn().mockResolvedValue(['cached-accepted']),+ set: jest.fn().mockResolvedValue(true),+ delete: jest.fn().mockRejectedValue(new Error('redis unavailable')),+ };+ const delay = jest.fn().mockResolvedValue(undefined);+ const cached = createUserMethods(mongoose, { getCache: () => cache, delay });++ await cached.resetTermsAcceptance();++ expect(delay).toHaveBeenCalledWith(AUTH_USER_DOC_MAX_AGE_MS + 100);});it('does not wait when the auth user cache is off', async () => {@@ -1492,6 +1520,7 @@ describe('User Methods - Database Tests', () => {});const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${user._id?.toString()}`;const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn().mockResolvedValue(['auth-cache-key-a']),delete: jest.fn().mockResolvedValue(true),};@@ -1735,6 +1764,7 @@ describe('User Methods - Database Tests', () => {);const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn().mockResolvedValue(['auth-cache-key-a']),delete: jest.fn().mockResolvedValue(true),};@@ -2096,6 +2126,7 @@ describe('User Methods - Database Tests', () => {const userId = user._id?.toString() ?? '';const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`;const cache = {+ set: jest.fn().mockResolvedValue(true),get: jest.fn().mockResolvedValue(['auth-cache-key-a']),delete: jest.fn().mockResolvedValue(true),};diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.tsindex f8123c7199..22e153bb8b 100644--- a/packages/data-schemas/src/methods/user.ts+++ b/packages/data-schemas/src/methods/user.ts@@ -1,5 +1,5 @@import mongoose, { FilterQuery } from 'mongoose';-import { AUTH_USER_DOC_CACHE_TTL_MS, CacheKeys } from 'librechat-data-provider';+import { AUTH_USER_DOC_MAX_AGE_MS } from 'librechat-data-provider';import type {BalanceRefillMode,RefillIntervalUnit,@@ -17,7 +17,7 @@ import type {import type { TwoFactorEnrollmentGuard, TwoFactorEnrollmentUpdate } from '~/types';import type { CacheStore } from '~/types';import { scoreSearchMatch, buildUserSearchFilter } from '~/utils/search';-import { evictAuthUserDocs } from '~/utils/eviction';+import { evictAuthUserDocsForUsers } from '~/utils/eviction';import { signPayload } from '~/crypto';import logger from '~/config/winston';@@ -41,16 +41,12 @@ interface UserMethodDeps {const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));-/** Timers can fire a millisecond early, so the wait outlasts the cache TTL by this much. */+/** Timers can fire a millisecond early, so the wait outlasts a cached document by this much. */const AUTH_USER_DOC_EXPIRY_MARGIN_MS = 100;/** Cached auth documents evicted at once when a reset touches every user. */const TERMS_RESET_EVICTION_BATCH = 100;-function isAuthUserDocCacheEnabled(): boolean {- return process.env.AUTH_USER_CACHE_MODE === 'on';-}-/** Factory function that takes mongoose instance and returns the methods */export function createUserMethods(mongoose: typeof import('mongoose'),@@ -443,7 +439,8 @@ export function createUserMethods(* The barrier a credential change passes before it is confirmed. A cached document without* the new credentialsChangedAt keeps pre-change access tokens verifying until it expires, so* eviction is retried and, when it still cannot remove every document, this resolves only- * after the cache TTL. Callers revoke sessions and passkeys first: during the wait those+ * after the longest a cached document can live, which a lookup that began just before the+ * change may stretch to two cache TTLs. Callers revoke sessions and passkeys first: during the wait those* could otherwise mint access tokens issued after the stamp.*/async function awaitAuthUserDocEviction(userId: string): Promise<void> {@@ -452,9 +449,9 @@ export function createUserMethods(}logger.warn('[awaitAuthUserDocEviction] Cached auth documents were not evicted after a credential change; waiting for them to expire',- { userId, waitMs: AUTH_USER_DOC_CACHE_TTL_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS },+ { userId, waitMs: AUTH_USER_DOC_MAX_AGE_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS },);- await (deps.delay ?? wait)(AUTH_USER_DOC_CACHE_TTL_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS);+ await (deps.delay ?? wait)(AUTH_USER_DOC_MAX_AGE_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS);}/** Only the request that atomically consumes an unused recovery code may authenticate. */@@ -527,18 +524,7 @@ export function createUserMethods(/** Resolves false only when a cached document for the user may still be served. */async function invalidateAuthUserDocCache(userId: string): Promise<boolean> {- if (!isAuthUserDocCacheEnabled()) {- return true;- }- const cache = deps.getCache?.(CacheKeys.AUTH_USER_DOC);- if (!cache?.get) {- return true;- }- const remove = cache.delete?.bind(cache);- if (!remove) {- return false;- }- return evictAuthUserDocs({ get: (key) => cache.get(key), delete: remove }, { userId });+ return evictAuthUserDocsForUsers(deps.getCache, [userId]);}/**@@ -566,24 +552,25 @@ export function createUserMethods();/** Every user, not only those read as accepted beforehand: an acceptance racing the update may be cached. */const cursor = User.find({}).select('_id').lean().cursor();+ let evicted = true;let batch: string[] = [];for await (const user of cursor) {batch.push(String(user._id));if (batch.length === TERMS_RESET_EVICTION_BATCH) {- await Promise.all(batch.map(invalidateAuthUserDocCache));+ evicted = (await evictAuthUserDocsForUsers(deps.getCache, batch)) && evicted;batch = [];}}- await Promise.all(batch.map(invalidateAuthUserDocCache));- if (isAuthUserDocCacheEnabled()) {- /**- * A request that read the old document before the update can still fill the cache after- * the eviction above, so no eviction result proves the reset took effect. Only expiry does.- */- logger.info('[resetTermsAcceptance] Waiting for cached auth documents to expire', {- waitMs: AUTH_USER_DOC_CACHE_TTL_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS,- });- await (deps.delay ?? wait)(AUTH_USER_DOC_CACHE_TTL_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS);+ evicted = (await evictAuthUserDocsForUsers(deps.getCache, batch)) && evicted;+ if (!evicted) {+ /** The eviction fence keeps requests that read the old document from caching it, so only a failed eviction needs to outlast the TTL. */+ logger.warn(+ '[resetTermsAcceptance] Cached auth documents were not evicted; waiting for them to expire',+ {+ waitMs: AUTH_USER_DOC_MAX_AGE_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS,+ },+ );+ await (deps.delay ?? wait)(AUTH_USER_DOC_MAX_AGE_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS);}return { modifiedCount: result.modifiedCount };}diff --git a/packages/data-schemas/src/utils/eviction.spec.ts b/packages/data-schemas/src/utils/eviction.spec.tsindex 4114788ab5..7d24886136 100644--- a/packages/data-schemas/src/utils/eviction.spec.ts+++ b/packages/data-schemas/src/utils/eviction.spec.ts@@ -1,11 +1,21 @@-import { AUTH_USER_DOC_BY_ID_PREFIX } from 'librechat-data-provider';-import { evictAuthUserDocs } from './eviction';+import {+ CacheKeys,+ AUTH_USER_DOC_BY_ID_PREFIX,+ AUTH_USER_DOC_EVICTION_FENCE_TTL_MS,+} from 'librechat-data-provider';+import type { CacheStore } from '~/types';+import {+ evictAuthUserDocs,+ evictAuthUserDocsForUsers,+ isAuthUserDocEvictionFenced,+ buildAuthUserDocEvictionFenceKey,+} from './eviction';const INDEX_KEY = `${AUTH_USER_DOC_BY_ID_PREFIX}:user-1`;const OTHER_INDEX_KEY = `${AUTH_USER_DOC_BY_ID_PREFIX}:user-2`;/** A Map-backed store that rejects the operations named for a key, as a throwing Redis store does. */-function makeStore(failures: { get?: string[]; delete?: string[] } = {}) {+function makeStore(failures: { get?: string[]; set?: string[]; delete?: string[] } = {}) {const values = new Map<string, unknown>([[INDEX_KEY, ['doc-a', 'doc-b']],['doc-a', { id: 'user-1' }],@@ -22,6 +32,13 @@ function makeStore(failures: { get?: string[]; delete?: string[] } = {}) {}return values.get(key);}),+ set: jest.fn(async (key: string, value: unknown, _ttl?: number) => {+ if (failures.set?.includes(key)) {+ throw new Error(`SET ${key} failed`);+ }+ values.set(key, value);+ return true;+ }),delete: jest.fn(async (key: string) => {if (failures.delete?.includes(key)) {throw new Error(`DEL ${key} failed`);@@ -108,4 +125,102 @@ describe('evictAuthUserDocs', () => {expect(store.values.get(INDEX_KEY)).toEqual(['doc-a', 'doc-b']);expectOtherUserCached(store);});++ it('fences the user for longer than a document read before the eviction can live', async () => {+ const store = makeStore();++ await expect(evictAuthUserDocs(store, { userId: 'user-1' })).resolves.toBe(true);++ expect(store.set).toHaveBeenCalledWith(+ buildAuthUserDocEvictionFenceKey('user-1'),+ expect.any(Number),+ AUTH_USER_DOC_EVICTION_FENCE_TTL_MS,+ );+ await expect(isAuthUserDocEvictionFenced(store, 'user-1')).resolves.toBe(true);+ await expect(isAuthUserDocEvictionFenced(store, 'user-2')).resolves.toBe(false);+ });++ it('reports a failed fence write even when every document was deleted', async () => {+ const store = makeStore({ set: [buildAuthUserDocEvictionFenceKey('user-1')] });++ await expect(evictAuthUserDocs(store, { userId: 'user-1' })).resolves.toBe(false);++ expect(store.values.has('doc-a')).toBe(false);+ expect(store.values.has('doc-b')).toBe(false);+ expect(store.values.get(INDEX_KEY)).toEqual(['doc-a', 'doc-b']);+ });++ it('does not fence when only a cache key is evicted', async () => {+ const store = makeStore();++ await expect(evictAuthUserDocs(store, { cacheKey: 'doc-c' })).resolves.toBe(true);++ expect(store.set).not.toHaveBeenCalled();+ expect(store.values.has('doc-c')).toBe(false);+ });+});++describe('isAuthUserDocEvictionFenced', () => {+ it('treats an unreadable fence as fenced', async () => {+ const store = makeStore({ get: [buildAuthUserDocEvictionFenceKey('user-1')] });++ await expect(isAuthUserDocEvictionFenced(store, 'user-1')).resolves.toBe(true);+ });+});++describe('evictAuthUserDocsForUsers', () => {+ const originalMode = process.env.AUTH_USER_CACHE_MODE;++ afterEach(() => {+ if (originalMode === undefined) {+ delete process.env.AUTH_USER_CACHE_MODE;+ } else {+ process.env.AUTH_USER_CACHE_MODE = originalMode;+ }+ });++ function cacheFor(store: ReturnType<typeof makeStore>) {+ return jest.fn((key: string) =>+ key === CacheKeys.AUTH_USER_DOC ? (store as CacheStore) : undefined,+ );+ }++ it('evicts and fences each distinct user once', async () => {+ process.env.AUTH_USER_CACHE_MODE = 'on';+ const store = makeStore();++ await expect(+ evictAuthUserDocsForUsers(cacheFor(store), [+ 'user-1',+ { toString: () => 'user-1' },+ 'user-2',+ ]),+ ).resolves.toBe(true);++ for (const key of [INDEX_KEY, OTHER_INDEX_KEY, 'doc-a', 'doc-b', 'doc-other']) {+ expect(store.values.has(key)).toBe(false);+ }+ expect(store.set).toHaveBeenCalledTimes(2);+ });++ it('reports a user whose documents may still be served', async () => {+ process.env.AUTH_USER_CACHE_MODE = 'on';+ const store = makeStore({ delete: ['doc-other'] });++ await expect(evictAuthUserDocsForUsers(cacheFor(store), ['user-1', 'user-2'])).resolves.toBe(+ false,+ );+ expect(store.values.has('doc-a')).toBe(false);+ });++ it('leaves the cache alone when the auth user cache is off', async () => {+ delete process.env.AUTH_USER_CACHE_MODE;+ const store = makeStore();+ const getCache = cacheFor(store);++ await expect(evictAuthUserDocsForUsers(getCache, ['user-1'])).resolves.toBe(true);++ expect(getCache).not.toHaveBeenCalled();+ expect(store.values.get(INDEX_KEY)).toEqual(['doc-a', 'doc-b']);+ });});diff --git a/packages/data-schemas/src/utils/eviction.ts b/packages/data-schemas/src/utils/eviction.tsindex f238b38a32..c6243f7b04 100644--- a/packages/data-schemas/src/utils/eviction.ts+++ b/packages/data-schemas/src/utils/eviction.ts@@ -1,12 +1,49 @@-import { AUTH_USER_DOC_BY_ID_PREFIX } from 'librechat-data-provider';+import {+ CacheKeys,+ AUTH_USER_DOC_BY_ID_PREFIX,+ AUTH_USER_DOC_EVICTED_PREFIX,+ AUTH_USER_DOC_EVICTION_FENCE_TTL_MS,+} from 'librechat-data-provider';+import type { CacheStore } from '~/types';import logger from '~/config/winston';/** Store operations eviction needs; a failure is only seen when the store throws it. */export interface AuthUserDocEvictionStore {get: (key: string) => Promise<unknown>;+ set: (key: string, value: unknown, ttl?: number) => Promise<unknown>;delete: (key: string) => Promise<unknown>;}+/** Users evicted at once by a bulk mutation. */+const EVICTION_BATCH = 100;++export function isAuthUserDocCacheEnabled(): boolean {+ return process.env.AUTH_USER_CACHE_MODE === 'on';+}++export function buildAuthUserDocEvictionFenceKey(userId: string): string {+ return `${AUTH_USER_DOC_EVICTED_PREFIX}:${userId}`;+}++/**+ * True while an eviction of the user is recent enough that a document read before it may still+ * be cached. A failed read counts as fenced, so an unreadable fence never serves a document.+ */+export async function isAuthUserDocEvictionFenced(+ store: Pick<AuthUserDocEvictionStore, 'get'>,+ userId: string,+): Promise<boolean> {+ try {+ return (await store.get(buildAuthUserDocEvictionFenceKey(userId))) != null;+ } catch (error) {+ logger.warn('[authUserDocCache] Eviction fence read failed; skipping the cached document', {+ userId,+ error: describeError(error),+ });+ return true;+ }+}+function isKeyList(value: unknown): value is string[] {return Array.isArray(value) && value.every((key) => typeof key === 'string');}@@ -17,8 +54,11 @@ function describeError(error: unknown): string {/*** Deletes the cached auth user documents for a user, attempting every delete even when- * another fails. Resolves false when a document may still be served: the reverse index could- * not be read, so its keys are unknown, or a document delete failed. The index is deleted only+ * another fails. A user eviction first writes a fence that outlives every document read before+ * it: a request that looked the user up before the change cannot cache or serve that document,+ * including one the reverse index never named. Resolves false when any step failed (the fence+ * write, the index read, so its keys are unknown, or a document delete), so a caller that must+ * prove the eviction stays conservative. The index is deleted only* after every document it names is gone, so a retry can still find what an earlier attempt* left behind. A failed delete of the index alone leaves only the names of deleted keys, so it* is logged and still counts as evicted. Never throws, so callers keep their own write results.@@ -29,7 +69,23 @@ export async function evictAuthUserDocs(): Promise<boolean> {const keys = new Set<string>(input.cacheKey ? [input.cacheKey] : []);const indexKey = input.userId ? `${AUTH_USER_DOC_BY_ID_PREFIX}:${input.userId}` : undefined;+ let fenced = true;let indexRead = true;+ if (input.userId) {+ try {+ await store.set(+ buildAuthUserDocEvictionFenceKey(input.userId),+ Date.now(),+ AUTH_USER_DOC_EVICTION_FENCE_TTL_MS,+ );+ } catch (error) {+ fenced = false;+ logger.warn('[authUserDocCache] Eviction fence write failed', {+ userId: input.userId,+ error: describeError(error),+ });+ }+ }if (indexKey) {try {const indexed = await store.get(indexKey);@@ -59,7 +115,7 @@ export async function evictAuthUserDocs(});}}- if (!indexRead || !documentsDeleted) {+ if (!fenced || !indexRead || !documentsDeleted) {return false;}@@ -75,3 +131,40 @@ export async function evictAuthUserDocs(}return true;}++/**+ * Evicts the cached auth user documents of every listed user, a batch at a time. Resolves true+ * when the cache is off or absent, and false when any user's documents may still be served.+ */+export async function evictAuthUserDocsForUsers(+ getCache: ((key: string) => CacheStore | undefined) | undefined,+ userIds: Iterable<string | { toString(): string }>,+): Promise<boolean> {+ if (!isAuthUserDocCacheEnabled()) {+ return true;+ }+ const cache = getCache?.(CacheKeys.AUTH_USER_DOC);+ if (!cache?.get) {+ return true;+ }+ const remove = cache.delete?.bind(cache);+ if (!remove) {+ return false;+ }+ const store: AuthUserDocEvictionStore = {+ get: (key) => cache.get(key),+ set: (key, value, ttl) => cache.set(key, value, ttl),+ delete: remove,+ };+ const ids = [...new Set([...userIds].map((userId) => userId.toString()))];+ let evicted = true;+ for (let start = 0; start < ids.length; start += EVICTION_BATCH) {+ const results = await Promise.all(+ ids+ .slice(start, start + EVICTION_BATCH)+ .map((userId) => evictAuthUserDocs(store, { userId })),+ );+ evicted = evicted && results.every(Boolean);+ }+ return evicted;+}