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 ACL Viewers and Surface Revocation Failures When Removing Shared MCP Servers (#17506)
Marco Berettaa0f063b1c76d
diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.jsindex df5d84d989..0c377973a5 100644--- a/api/server/controllers/UserController.js+++ b/api/server/controllers/UserController.js@@ -166,6 +166,7 @@ const createMCPServerCleanup = (userId) => ({},findMCPServerOAuthTokenUserIds: db.findMCPServerOAuthTokenUserIds,findMCPServerViewerEntries: db.findMCPServerViewerEntries,+ findMCPServerViewerUserIds: db.findMCPServerViewerUserIds,mcpOAuth: {getServerConfig: (serverName) =>getMCPServersRegistry().getServerConfig(serverName, userId, undefined, undefined, {diff --git a/api/server/controllers/__tests__/mcp.servers.spec.js b/api/server/controllers/__tests__/mcp.servers.spec.jsindex d8f59e8a08..20b8981019 100644--- a/api/server/controllers/__tests__/mcp.servers.spec.js+++ b/api/server/controllers/__tests__/mcp.servers.spec.js@@ -543,6 +543,7 @@ describe('DB-backed server mutation fencing', () => {},},expect.objectContaining({ source: 'user' }),+ { strictRevocation: undefined, retainFence: undefined },);expect(invalidateCachedTools.mock.invocationCallOrder[0]).toBeLessThan(mockRegistryInstance.removeServer.mock.invocationCallOrder[0],@@ -588,6 +589,7 @@ describe('DB-backed server mutation fencing', () => {'mcp_github',expect.any(Object),expect.objectContaining({ dbId: dbId.toString() }),+ { strictRevocation: undefined, retainFence: undefined },);expect(require('~/server/services/Config').invalidateCachedTools).toHaveBeenCalledWith({userId: sharedUser.id,@@ -599,6 +601,43 @@ describe('DB-backed server mutation fencing', () => {}});+ it('fences a viewer who holds no OAuth token when the server is deleted', async () => {+ const owner = await createUser();+ const viewer = await createUser();+ const dbId = new mongoose.Types.ObjectId();+ await grantPermission({+ principalType: PrincipalType.USER,+ principalId: viewer.id,+ resourceType: ResourceType.MCPSERVER,+ resourceId: dbId,+ accessRoleId: AccessRoleIds.MCPSERVER_VIEWER,+ grantedBy: owner.id,+ });+ mockRegistryInstance.getServerConfig.mockResolvedValue(createDbConfig(dbId));+ mockRegistryInstance.removeServer.mockResolvedValue(undefined);+ const res = createRes();++ await deleteMCPServerController(+ { user: owner, params: { serverName: 'github' } },+ res,+ mockMaybeUninstallOAuthMCP,+ );++ expect(require('~/server/services/Config').invalidateCachedTools).toHaveBeenCalledWith({+ userId: viewer.id,+ serverName: 'github',+ });+ expect(mockMcpManager.disconnectUserConnection).toHaveBeenCalledWith(viewer.id, 'github');+ expect(mockMaybeUninstallOAuthMCP).toHaveBeenCalledWith(+ viewer.id,+ 'mcp_github',+ expect.any(Object),+ expect.objectContaining({ dbId: dbId.toString() }),+ { strictRevocation: undefined, retainFence: undefined },+ );+ expect(res.status).toHaveBeenCalledWith(200);+ });+it('does not delete the registry entry when the distributed fence fails', async () => {const user = await createUser();require('~/server/services/Config').invalidateCachedTools.mockRejectedValue(diff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.jsindex cd51ee80e8..89bfbef20a 100644--- a/api/server/controllers/mcp.js+++ b/api/server/controllers/mcp.js@@ -678,7 +678,11 @@ const deleteMCPServerController = async (req, res, uninstallOAuthMCP) => {}).lean(): Promise.resolve([]);const [oauthDeletionSnapshot, retainedTools] = await Promise.all([- prepareMCPServerOAuthDeletion({ getTokenUserIds, getAclEntries }),+ prepareMCPServerOAuthDeletion({+ getTokenUserIds,+ getAclEntries,+ getViewerUserIds: db.findMCPServerViewerUserIds,+ }),getMCPServerTools(userId, serverName, existingConfig),]);await invalidateCachedTools({ userId, serverName });diff --git a/api/server/services/MCP/oauthCleanup.js b/api/server/services/MCP/oauthCleanup.jsindex 9064bae25d..a1dabf22e7 100644--- a/api/server/services/MCP/oauthCleanup.js+++ b/api/server/services/MCP/oauthCleanup.js@@ -7,13 +7,20 @@ const db = require('~/models');/** Revocation must still reach a server the owner's profile hides. */const INCLUDE_HIDDEN = { includeHidden: true };-const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig, serverConfigOverride) => {+const maybeUninstallOAuthMCP = async (+ userId,+ pluginKey,+ appConfig,+ serverConfigOverride,+ teardown,+) => {const registry = getMCPServersRegistry();return cleanupMCPServerOAuth({userId,pluginKey,appConfig,serverConfigOverride,+ teardown,dependencies: {flowManager: getFlowStateManager(getLogStores(CacheKeys.FLOWS)),oauthHandler: MCPOAuthHandler,diff --git a/config/delete-user.js b/config/delete-user.jsindex e7e161e00c..d56e9262d3 100644--- a/config/delete-user.js+++ b/config/delete-user.js@@ -231,6 +231,8 @@ async function gracefulExit(code = 0) {),findMCPServerViewerEntries: (serverId) =>runInUserTenant(async () => methods.findMCPServerViewerEntries(serverId)),+ findMCPServerViewerUserIds: (entries) =>+ runInUserTenant(async () => methods.findMCPServerViewerUserIds(entries)),invalidateMCPServerTools: (serverName) =>invalidateCachedTools({ userId: uid, serverName }),/** The CLI has no MCP registry or live connections, so shared users get local token and cache cleanup. */@@ -256,13 +258,14 @@ async function gracefulExit(code = 0) {runInUserTenant(async () =>invalidateCachedTools({ userId: candidateId, serverName }),),- uninstallOAuthMCP: (candidateId, pluginKey, cleanupConfig, serverConfig) =>+ uninstallOAuthMCP: (candidateId, pluginKey, cleanupConfig, serverConfig, teardown) =>runInUserTenant(async () =>cleanupMCPServerOAuth({userId: candidateId,pluginKey,appConfig: cleanupConfig,serverConfigOverride: serverConfig,+ teardown,dependencies: {flowManager: getFlowStateManager(getLogStores(CacheKeys.FLOWS)),oauthHandler: MCPOAuthHandler,diff --git a/e2e/specs/mock/scenarios/mcp-server-removal-oauth.spec.ts b/e2e/specs/mock/scenarios/mcp-server-removal-oauth.spec.tsnew file mode 100644index 0000000000..c89a868664--- /dev/null+++ b/e2e/specs/mock/scenarios/mcp-server-removal-oauth.spec.ts@@ -0,0 +1,108 @@+import { resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { expect, test } from '@playwright/test';+import { inOneProject, repoRoot } from './lint.helpers';++/**+ * Removing a shared MCP server, by deleting it or by erasing its owner's account, fences every+ * viewer and tears down their OAuth state. The behavior is pinned by specs that run the real+ * teardown against MongoDB (the token store, its encryption, the ACLs and groups) with only the+ * provider's revocation endpoint replaced; each scenario reads one verdict from a single jest run+ * per workspace. None of them needs the browser.+ */++type JestAssertion = { ancestorTitles: string[]; title: string; status: string };+type JestReport = { testResults: { assertionResults: JestAssertion[] }[] };++const JEST = resolve(repoRoot, 'node_modules/.bin/jest');++const SUITES = {+ erasure: { cwd: 'packages/api', spec: 'src/user/erasure.spec.ts' },+ cleanup: { cwd: 'packages/api', spec: 'src/mcp/oauth/cleanup.test.ts' },+ route: { cwd: 'api', spec: 'server/controllers/__tests__/mcp.servers.spec.js' },+} as const;++const reports = new Map<keyof typeof SUITES, JestAssertion[]>();++/**+ * Runs a suite once per worker and keeps every verdict it reports. The run is bounded on its own,+ * since a synchronous child blocks the test timeout, and a nonzero exit fails the scenario even+ * when every assertion passed, as a suite-level error does.+ */+function suiteResults(suite: keyof typeof SUITES): JestAssertion[] {+ const cached = reports.get(suite);+ if (cached) {+ return cached;+ }+ const { cwd, spec } = SUITES[suite];+ const result = spawnSync(JEST, [spec, '--json', '--maxWorkers=2'], {+ cwd: resolve(repoRoot, cwd),+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ timeout: 240_000,+ });+ const stdout = result.stdout ?? '';+ const output = `${stdout}${result.stderr ?? ''}`;+ if (result.error || result.status !== 0) {+ throw new Error(`jest did not pass (${result.error?.message ?? result.status}):\n${output}`);+ }+ const start = stdout.indexOf('{');+ if (start === -1) {+ throw new Error(`jest printed no JSON report:\n${output}`);+ }+ const parsed = JSON.parse(stdout.slice(start)) as JestReport;+ const assertions = parsed.testResults.flatMap((file) => file.assertionResults);+ reports.set(suite, assertions);+ return assertions;+}++const expectPassed = (suite: keyof typeof SUITES, title: string) => {+ const assertion = suiteResults(suite).find((entry) => entry.title === title);+ expect(assertion, `no ${suite} spec named "${title}"`).toBeDefined();+ expect(assertion?.status).toBe('passed');+};++test.describe('removing a shared MCP server', () => {+ test.beforeEach(() => {+ inOneProject();+ test.setTimeout(300_000);+ });++ test('account erasure fences viewers named by the server ACL or a group, token or not @scenario:server-removal-fences-acl-only-viewers', () => {+ expectPassed(+ 'erasure',+ 'fences viewers who reach the server through its ACL without an OAuth token',+ );+ });++ test('deleting a server fences a viewer who holds no OAuth token @scenario:server-delete-route-fences-acl-only-viewers', () => {+ expectPassed('route', 'fences a viewer who holds no OAuth token when the server is deleted');+ });++ test('a refused provider revocation does not block erasure: local credentials are cleared, the server is removed and the grant is reported @scenario:erasure-surfaces-provider-revocation-failure', () => {+ expectPassed(+ 'erasure',+ 'removes the server and reports the grant when the provider refuses a revocation',+ );+ expectPassed('cleanup', 'clears local credentials and then rejects in strict mode');+ expectPassed('cleanup', 'returns refused revocations instead of failing the cleanup');+ });++ test('a local token delete failure fails erasure closed and a retry finishes it @scenario:erasure-fails-closed-on-local-teardown-failure', () => {+ expectPassed('erasure', 'fails closed, keeping the server, when a local token delete fails');+ expectPassed('cleanup', 'still fails the cleanup on a local teardown failure');+ });++ test('no authorization or refresh can take the OAuth fence until the server delete commits @scenario:erasure-holds-oauth-fence-through-delete', () => {+ expectPassed('erasure', 'holds every OAuth teardown fence until the server delete commits');+ expectPassed('erasure', 'releases every held fence when a teardown fails locally');+ expectPassed(+ 'erasure',+ 'keeps the server when a held fence lapsed and another writer took it before the delete',+ );+ });++ test('a user removing their own MCP connection still succeeds when the provider refuses revocation @scenario:own-connection-removal-stays-best-effort', () => {+ expectPassed('cleanup', 'stays best effort for a user removing their own connection');+ });+});diff --git a/packages/api/src/flow/manager.test.ts b/packages/api/src/flow/manager.test.tsindex 43a8d9c78b..6c8b28d217 100644--- a/packages/api/src/flow/manager.test.ts+++ b/packages/api/src/flow/manager.test.ts@@ -1608,6 +1608,27 @@ describe('FlowStateManager', () => {await second?.release();});+ it('renews a held lease and refuses once another owner took it after expiry', async () => {+ const now = Date.now();+ const clock = jest.spyOn(Date, 'now').mockReturnValue(now);+ const held = await flowManager.acquireLease('renewed-owner', {+ advanceGeneration: true,+ leaseMs: 1_000,+ });++ clock.mockReturnValue(now + 900);+ await expect(held?.renew?.()).resolves.toBe(true);+ clock.mockReturnValue(now + 1_500);+ await expect(flowManager.acquireLease('renewed-owner', { waitMs: 0 })).resolves.toBeNull();++ clock.mockReturnValue(now + 3_000);+ const intruder = await flowManager.acquireLease('renewed-owner', { waitMs: 0 });+ expect(intruder).not.toBeNull();+ await intruder?.release();+ await expect(held?.renew?.()).resolves.toBe(false);+ clock.mockRestore();+ });+it('expires released in-memory generations after the stale-work horizon', async () => {const now = Date.now();const clock = jest.spyOn(Date, 'now').mockReturnValue(now);diff --git a/packages/api/src/flow/manager.ts b/packages/api/src/flow/manager.tsindex 54979587b7..c11557b826 100644--- a/packages/api/src/flow/manager.ts+++ b/packages/api/src/flow/manager.ts@@ -11,6 +11,11 @@ type GuardedMutationResult = 'updated' | 'stale' | 'missing';export interface FlowLease {generation: number;release: () => Promise<void>;+ /**+ * Extends the lease while this owner still holds it. Resolves false once anyone else acquired+ * it after expiry, so a holder can tell an unbroken fence from a lapsed one.+ */+ renew?: () => Promise<boolean>;}/** The flow a waiter was monitoring disappeared before it settled. */@@ -144,6 +149,16 @@ redis.call('SET', KEYS[1], cjson.encode(data), 'PX', ARGV[6])return data.generation`;+const RENEW_LEASE = `+local raw = redis.call('GET', KEYS[1])+if not raw then return -1 end+local data = cjson.decode(raw)+if data.owner ~= ARGV[1] then return -1 end+data.leaseUntil = tonumber(ARGV[2]) + tonumber(ARGV[3])+redis.call('SET', KEYS[1], cjson.encode(data), 'PX', ARGV[4])+return 1+`;+const RELEASE_LEASE = `local raw = redis.call('GET', KEYS[1])if not raw then return 0 end@@ -336,6 +351,30 @@ export class FlowStateManager<T = unknown> {});}},+ renew: async () => {+ const renewedAt = Date.now();+ if (redisKey) {+ const renewed = Number(+ await this.evalRedisScript(RENEW_LEASE, redisKey, [+ owner,+ String(renewedAt),+ String(leaseMs),+ String(retentionMs),+ ]),+ );+ return renewed === 1;+ }+ const current = FlowStateManager.inMemoryLeases.get(inMemoryKey);+ if (current?.owner !== owner) {+ return false;+ }+ FlowStateManager.inMemoryLeases.set(inMemoryKey, {+ ...current,+ leaseUntil: renewedAt + leaseMs,+ expiresAt: renewedAt + retentionMs,+ });+ return true;+ },};}if (Date.now() >= waitUntil) return null;diff --git a/packages/api/src/mcp/oauth/cleanup.test.ts b/packages/api/src/mcp/oauth/cleanup.test.tsindex 299628b81d..32f1d675f0 100644--- a/packages/api/src/mcp/oauth/cleanup.test.ts+++ b/packages/api/src/mcp/oauth/cleanup.test.ts@@ -1,5 +1,12 @@+import type { MCPOAuthCleanupDependencies } from './cleanup';import type { ParsedServerConfig } from '~/mcp/types';-import { cleanupMCPServerOAuth, getMCPServerGeneration } from './cleanup';+import {+ cleanupMCPServerOAuth,+ getMCPServerGeneration,+ MCPOAuthRevocationError,+ MCP_OAUTH_REVOCATION_REFUSED,+ cleanupDeletedMCPServerOAuthUsers,+} from './cleanup';const createFlowManager = () => ({acquireLease: jest.fn().mockResolvedValue({@@ -285,4 +292,210 @@ describe('cleanupMCPServerOAuth', () => {expect(getTokens).not.toHaveBeenCalled();expect(revokeOAuthToken).not.toHaveBeenCalled();});++ describe('provider revocation failures', () => {+ const createRevocationDependencies = (revokeOAuthToken: jest.Mock) => {+ const deleteTokens = jest.fn();+ const findToken = jest.fn(async ({ type }: { type?: string }) => ({+ token: `encrypted-${type}`,+ metadata: { credential_set_id: 'generation-1' },+ })) as never;+ return {+ deleteTokens,+ dependencies: {+ flowManager: createFlowManager() as never,+ oauthHandler: {+ generateFlowId: jest.fn(() => 'user-1:test-server'),+ generateTokenFlowId: jest.fn(() => 'user-1:test-server'),+ deleteFlowAndStateMapping: jest.fn(),+ revokeOAuthToken,+ },+ tokenStorage: {+ deleteUserTokens: jest.fn(+ async ({+ userId,+ serverName,+ deleteToken,+ }: {+ userId: string;+ serverName: string;+ deleteToken: (filter: Record<string, string>) => Promise<void>;+ }) => {+ await deleteToken({ userId, type: 'mcp_oauth', identifier: `mcp:${serverName}` });+ },+ ),+ getClientInfoAndMetadata: jest.fn(async () => ({+ clientInfo: { client_id: 'client' },+ clientMetadata: {+ credential_set_id: 'generation-1',+ server_url: 'https://example.com/mcp',+ token_endpoint: 'https://auth.example.com/token',+ revocation_endpoint: 'https://auth.example.com/revoke',+ client_source: 'dynamic',+ },+ })),+ getTokens: jest.fn(async () => ({+ access_token: 'access',+ refresh_token: 'refresh',+ credential_set_id: 'generation-1',+ })),+ assertCredentialSetBinding: jest.fn(),+ } as unknown as MCPOAuthCleanupDependencies['tokenStorage'],+ findToken,+ deleteTokens,+ getServerConfig: jest.fn(),+ isRegisteredOAuthServer: jest.fn(),+ } satisfies MCPOAuthCleanupDependencies,+ };+ };+ const params = {+ userId: 'user-1',+ pluginKey: 'mcp_test-server',+ serverConfigOverride: {+ type: 'streamable-http' as const,+ url: 'https://example.com/mcp',+ oauth: {},+ },+ };++ it('stays best effort for a user removing their own connection', async () => {+ const revokeOAuthToken = jest.fn().mockRejectedValue(new Error('503'));+ const { deleteTokens, dependencies } = createRevocationDependencies(revokeOAuthToken);++ await expect(cleanupMCPServerOAuth({ ...params, dependencies })).resolves.toBeUndefined();+ expect(deleteTokens).toHaveBeenCalled();+ });++ it('clears local credentials and then rejects in strict mode', async () => {+ const revokeOAuthToken = jest+ .fn()+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error('503'));+ const { deleteTokens, dependencies } = createRevocationDependencies(revokeOAuthToken);++ await expect(+ cleanupMCPServerOAuth({ ...params, dependencies, teardown: { strictRevocation: true } }),+ ).rejects.toMatchObject({+ code: MCP_OAUTH_REVOCATION_REFUSED,+ tokenTypes: ['refresh'],+ message: 'OAuth provider did not revoke the refresh token for test-server',+ });+ expect(revokeOAuthToken).toHaveBeenCalledTimes(2);+ expect(deleteTokens).toHaveBeenCalled();+ });++ it('hands over the fence before reporting a refused revocation', async () => {+ const { dependencies } = createRevocationDependencies(+ jest.fn().mockRejectedValue(new Error('503')),+ );+ const retainFence = jest.fn();++ await expect(+ cleanupMCPServerOAuth({+ ...params,+ dependencies,+ teardown: { strictRevocation: true, retainFence },+ }),+ ).rejects.toMatchObject({ code: MCP_OAUTH_REVOCATION_REFUSED });+ expect(retainFence).toHaveBeenCalledTimes(1);+ const lease = await (dependencies.flowManager as ReturnType<typeof createFlowManager>)+ .acquireLease.mock.results[0].value;+ expect(lease.release).not.toHaveBeenCalled();+ await retainFence.mock.calls[0][0].release();+ expect(lease.release).toHaveBeenCalledTimes(1);+ });++ it('does not hand over a fence when a local token delete fails', async () => {+ const { dependencies } = createRevocationDependencies(jest.fn());+ dependencies.tokenStorage.deleteUserTokens = jest.fn(async () => {+ throw new Error('mongo down');+ });+ const retainFence = jest.fn();++ await expect(+ cleanupMCPServerOAuth({+ ...params,+ dependencies,+ teardown: { strictRevocation: true, retainFence },+ }),+ ).rejects.toThrow('Failed to delete stored MCP OAuth tokens for test-server');+ expect(retainFence).not.toHaveBeenCalled();+ const lease = await (dependencies.flowManager as ReturnType<typeof createFlowManager>)+ .acquireLease.mock.results[0].value;+ expect(lease.release).toHaveBeenCalledTimes(1);+ });+ });+});++describe('cleanupDeletedMCPServerOAuthUsers', () => {+ it('fences ACL-named viewers without a token and passes the teardown mode through', async () => {+ const fenceAndDisconnectUser = jest.fn(async (_userId: string) => undefined);+ const uninstallOAuthMCP = jest.fn(async () => undefined);+ const getUserPrincipals = jest.fn(async (_userId: string) => []);+ const retainFence = jest.fn();++ await cleanupDeletedMCPServerOAuthUsers({+ ownerUserId: 'owner',+ serverName: 'shared',+ snapshot: { tokenUserIds: ['stranger'], aclEntries: [], viewerUserIds: ['owner', 'viewer'] },+ getTokenUserIds: async () => [],+ getUserPrincipals,+ resolveAllowlists: async () => ({}),+ fenceAndDisconnectUser,+ uninstallOAuthMCP,+ strictRevocation: true,+ retainFence,+ });++ expect(fenceAndDisconnectUser.mock.calls.map(([userId]) => userId)).toEqual([+ 'owner',+ 'viewer',+ ]);+ expect(getUserPrincipals.mock.calls.map(([userId]) => userId)).toEqual(['stranger']);+ expect(uninstallOAuthMCP).toHaveBeenCalledWith(+ 'viewer',+ 'mcp_shared',+ { mcpSettings: {} },+ undefined,+ { strictRevocation: true, retainFence },+ );+ });++ it('returns refused revocations instead of failing the cleanup', async () => {+ const uninstallOAuthMCP = jest.fn(async (userId: string) => {+ if (userId === 'viewer') {+ throw new MCPOAuthRevocationError('shared', ['access']);+ }+ });++ const refusals = await cleanupDeletedMCPServerOAuthUsers({+ ownerUserId: 'owner',+ serverName: 'shared',+ snapshot: { tokenUserIds: [], aclEntries: [], viewerUserIds: ['viewer'] },+ getTokenUserIds: async () => [],+ getUserPrincipals: async () => [],+ resolveAllowlists: async () => ({}),+ uninstallOAuthMCP,+ strictRevocation: true,+ });++ expect(refusals).toEqual([{ userId: 'viewer', tokenTypes: ['access'] }]);+ });++ it('still fails the cleanup on a local teardown failure', async () => {+ await expect(+ cleanupDeletedMCPServerOAuthUsers({+ ownerUserId: 'owner',+ serverName: 'shared',+ snapshot: { tokenUserIds: [], aclEntries: [], viewerUserIds: ['viewer'] },+ getTokenUserIds: async () => [],+ getUserPrincipals: async () => [],+ resolveAllowlists: async () => ({}),+ uninstallOAuthMCP: async () => {+ throw new Error('mongo down');+ },+ strictRevocation: true,+ }),+ ).rejects.toThrow('OAuth cleanup failed for shared');+ });});diff --git a/packages/api/src/mcp/oauth/cleanup.ts b/packages/api/src/mcp/oauth/cleanup.tsindex 45de6c0984..168c70a60e 100644--- a/packages/api/src/mcp/oauth/cleanup.ts+++ b/packages/api/src/mcp/oauth/cleanup.ts@@ -33,19 +33,81 @@ export interface OAuthAclSubject {export interface MCPServerOAuthDeletionSnapshot {tokenUserIds: string[];aclEntries: OAuthAclSubject[];+ /** Users the view ACL names directly or through a group, whether or not they hold a token. */+ viewerUserIds?: string[];}interface PrepareDeletionParams {getTokenUserIds: () => Promise<Array<{ toString(): string } | string>>;getAclEntries: () => Promise<OAuthAclSubject[]>;+ getViewerUserIds?: (entries: OAuthAclSubject[]) => Promise<string[]>;}export async function prepareMCPServerOAuthDeletion({getTokenUserIds,getAclEntries,+ getViewerUserIds,}: PrepareDeletionParams): Promise<MCPServerOAuthDeletionSnapshot> {- const [tokenUserIds, aclEntries] = await Promise.all([getTokenUserIds(), getAclEntries()]);- return { tokenUserIds: tokenUserIds.map(String), aclEntries };+ const [tokenUserIds, { aclEntries, viewerUserIds }] = await Promise.all([+ getTokenUserIds(),+ getAclEntries().then(async (entries) => ({+ aclEntries: entries,+ viewerUserIds: getViewerUserIds ? (await getViewerUserIds(entries)).map(String) : [],+ })),+ ]);+ return { tokenUserIds: tokenUserIds.map(String), aclEntries, viewerUserIds };+}++export const MCP_OAUTH_REVOCATION_REFUSED = 'MCP_OAUTH_REVOCATION_REFUSED' as const;++/**+ * The provider did not revoke a grant. Local credentials are already gone when this is thrown,+ * so it reports an external grant that may stay valid rather than a teardown that failed.+ */+export class MCPOAuthRevocationError extends Error {+ readonly code: typeof MCP_OAUTH_REVOCATION_REFUSED = MCP_OAUTH_REVOCATION_REFUSED;+ constructor(+ readonly serverName: string,+ readonly tokenTypes: string[],+ ) {+ super(`OAuth provider did not revoke the ${tokenTypes.join(' and ')} token for ${serverName}`);+ this.name = 'MCPOAuthRevocationError';+ }+}++/** Matched by code, since hosts can load a second copy of this module. */+export function isMCPOAuthRevocationError(error: unknown): error is MCPOAuthRevocationError {+ return (+ error instanceof Error &&+ (error as Partial<MCPOAuthRevocationError>).code === MCP_OAUTH_REVOCATION_REFUSED+ );+}++/** A user whose provider grant may outlive the removed server. */+export interface MCPOAuthRevocationFailure {+ userId: string;+ tokenTypes: string[];+}++/** How a server-removal teardown treats the provider and the per-user OAuth fence. */+export interface MCPOAuthTeardownOptions {+ /**+ * Clears local state, then rejects with an `MCPOAuthRevocationError` when the provider refused a+ * revocation, so the caller learns which grants may stay valid.+ */+ strictRevocation?: boolean;+ /**+ * Receives a successful teardown's fence instead of releasing it, so the caller can keep new+ * authorizations and refreshes out until the server record is gone.+ */+ retainFence?: (fence: MCPOAuthRetainedFence) => void;+}++/** A teardown fence the caller holds past the teardown itself. */+export interface MCPOAuthRetainedFence {+ /** Extends the lease; false when it lapsed and another writer took it in the meantime. */+ renew: () => Promise<boolean>;+ release: () => Promise<void>;}interface CleanupDeletedUsersParams {@@ -64,7 +126,15 @@ interface CleanupDeletedUsersParams {pluginKey: string,appConfig: CleanupConfig,serverConfig?: MCPOptions,+ teardown?: MCPOAuthTeardownOptions,) => Promise<void>;+ /**+ * Set where the server record outlives this cleanup: refused revocations are returned instead of+ * logged only, and each user's fence is held until the record is deleted. A provider cannot fail+ * the cleanup, since it could otherwise block the removal indefinitely.+ */+ strictRevocation?: boolean;+ retainFence?: MCPOAuthTeardownOptions['retainFence'];}const OAUTH_CLEANUP_CONCURRENCY = 10;@@ -79,14 +149,23 @@ export async function cleanupDeletedMCPServerOAuthUsers({resolveAllowlists,fenceAndDisconnectUser,uninstallOAuthMCP,-}: CleanupDeletedUsersParams): Promise<void> {+ strictRevocation,+ retainFence,+}: CleanupDeletedUsersParams): Promise<MCPOAuthRevocationFailure[]> {const tokenUserIdsAfterDelete = (await getTokenUserIds()).map(String);const candidateUserIds = [...new Set([ownerUserId, ...snapshot.tokenUserIds, ...tokenUserIdsAfterDelete]),];- const affectedUserIds = [ownerUserId];- const sharedCandidates = candidateUserIds.filter((userId) => userId !== ownerUserId);+ /** Named by the view ACL itself, so they had access without a principal lookup. */+ const viewerUserIds = new Set(+ (snapshot.viewerUserIds ?? []).filter((userId) => userId !== ownerUserId),+ );+ const affectedUserIds = [ownerUserId, ...viewerUserIds];+ const sharedCandidates = candidateUserIds.filter(+ (userId) => userId !== ownerUserId && !viewerUserIds.has(userId),+ );const failures: unknown[] = [];+ const revocationFailures: MCPOAuthRevocationFailure[] = [];for (let offset = 0; offset < sharedCandidates.length; offset += OAUTH_CLEANUP_CONCURRENCY) {const batch = sharedCandidates.slice(offset, offset + OAUTH_CLEANUP_CONCURRENCY);@@ -132,9 +211,14 @@ export async function cleanupDeletedMCPServerOAuthUsers({`${Constants.mcp_prefix}${serverName}`,{ mcpSettings: { allowedDomains, allowedAddresses } },serverConfig,+ { strictRevocation, retainFence },);} catch (error) {- userFailures.push(error);+ if (isMCPOAuthRevocationError(error)) {+ revocationFailures.push({ userId, tokenTypes: error.tokenTypes });+ } else {+ userFailures.push(error);+ }}if (userFailures.length > 0) {throw new Error(`OAuth cleanup failed for user ${userId}`);@@ -154,6 +238,7 @@ export async function cleanupDeletedMCPServerOAuthUsers({if (failures.length > 0) {throw new Error(`OAuth cleanup failed for ${serverName} (${failures.length} operation(s))`);}+ return revocationFailures;}export interface MCPOAuthCleanupDependencies {@@ -183,6 +268,8 @@ interface ClearStateParams {skipOAuthFlows?: boolean;credentialSetId?: string | null;tokenSnapshot?: Map<string, string>;+ /** Rethrows a failed token delete after flow state is cleared. */+ strict?: boolean;}const oauthTokenKeys = (serverName: string) => {@@ -201,7 +288,9 @@ export async function clearStoredMCPOAuthState({skipOAuthFlows = false,credentialSetId,tokenSnapshot,+ strict = false,}: ClearStateParams): Promise<void> {+ let tokenDeleteError: unknown;try {await dependencies.tokenStorage.deleteUserTokens({userId,@@ -220,6 +309,7 @@ export async function clearStoredMCPOAuthState({},});} catch (error) {+ tokenDeleteError = error;logger.warn(`[clearStoredMCPOAuthState] Failed to delete MCP OAuth tokens for ${serverName}:`,error,@@ -260,6 +350,9 @@ export async function clearStoredMCPOAuthState({);}}+ if (strict && tokenDeleteError) {+ throw new Error(`Failed to delete stored MCP OAuth tokens for ${serverName}`);+ }}interface UninstallParams {@@ -268,6 +361,7 @@ interface UninstallParams {appConfig?: CleanupConfig;serverConfigOverride?: MCPOptions;dependencies: MCPOAuthCleanupDependencies;+ teardown?: MCPOAuthTeardownOptions;}export async function cleanupMCPServerOAuth(params: UninstallParams): Promise<void> {@@ -280,6 +374,14 @@ export async function cleanupMCPServerOAuth(params: UninstallParams): Promise<vo(await dependencies.tokenStorage.beginRefreshTeardown?.(userId, serverName)) ?? (() => {});let teardownLease: Awaited<ReturnType<typeof dependencies.flowManager.acquireLease>> = null;let leaseError: unknown;+ const releaseFence = async () => {+ try {+ await teardownLease?.release();+ } finally {+ releaseRefreshTeardown();+ }+ };+ let fenceRetained = false;try {try {teardownLease = await dependencies.flowManager.acquireLease(@@ -292,15 +394,34 @@ export async function cleanupMCPServerOAuth(params: UninstallParams): Promise<vo} catch (error) {leaseError = error;}- await cleanupMCPServerOAuthWithFenceHeld(params);+ let revocationError: MCPOAuthRevocationError | undefined;+ try {+ await cleanupMCPServerOAuthWithFenceHeld(params);+ } catch (error) {+ if (!isMCPOAuthRevocationError(error)) {+ throw error;+ }+ revocationError = error;+ }if (leaseError) {throw leaseError;}+ const retainFence = params.teardown?.retainFence;+ if (retainFence) {+ const lease = teardownLease;+ retainFence({+ renew: async () => (lease?.renew ? lease.renew() : lease != null),+ release: releaseFence,+ });+ fenceRetained = true;+ }+ /** Local state is cleared and the fence is handed over; only the provider grant remains. */+ if (revocationError) {+ throw revocationError;+ }} finally {- try {- await teardownLease?.release();- } finally {- releaseRefreshTeardown();+ if (!fenceRetained) {+ await releaseFence();}}}@@ -311,7 +432,9 @@ async function cleanupMCPServerOAuthWithFenceHeld({appConfig,serverConfigOverride,dependencies,+ teardown,}: UninstallParams): Promise<void> {+ const strict = teardown?.strictRevocation === true;const serverName = pluginKey.replace(Constants.mcp_prefix, '');/** Snapshot exact encrypted values before cancelling the flow. Later cleanup can then remove* this authorization without matching credentials written by a replacement attempt. */@@ -464,6 +587,7 @@ async function cleanupMCPServerOAuthWithFenceHeld({dependencies,skipOAuthFlows: true,tokenSnapshot,+ strict,});return;}@@ -475,6 +599,7 @@ async function cleanupMCPServerOAuthWithFenceHeld({dependencies,skipOAuthFlows: true,tokenSnapshot,+ strict,});return;}@@ -500,6 +625,7 @@ async function cleanupMCPServerOAuthWithFenceHeld({skipOAuthFlows: true,credentialSetId: typeof credentialSetId === 'string' ? credentialSetId : null,tokenSnapshot,+ strict,});return;}@@ -520,6 +646,7 @@ async function cleanupMCPServerOAuthWithFenceHeld({const oauthHeaders = serverConfig.oauth_headers ?? {};const allowedDomains = appConfig?.mcpSettings?.allowedDomains;const allowedAddresses = appConfig?.mcpSettings?.allowedAddresses;+ const revocationFailures: string[] = [];for (const [tokenType, token] of [['access', tokens?.access_token],['refresh', tokens?.refresh_token],@@ -538,6 +665,7 @@ async function cleanupMCPServerOAuthWithFenceHeld({allowedAddresses,);} catch (error) {+ revocationFailures.push(tokenType);logger.error(`[maybeUninstallOAuthMCP] Error revoking ${tokenType} token:`, error);}}@@ -549,5 +677,9 @@ async function cleanupMCPServerOAuthWithFenceHeld({skipOAuthFlows: true,credentialSetId,tokenSnapshot,+ strict,});+ if (strict && revocationFailures.length > 0) {+ throw new MCPOAuthRevocationError(serverName, revocationFailures);+ }}diff --git a/packages/api/src/user/erasure.spec.ts b/packages/api/src/user/erasure.spec.tsindex da3937a313..c78300d55c 100644--- a/packages/api/src/user/erasure.spec.ts+++ b/packages/api/src/user/erasure.spec.ts@@ -1,3 +1,4 @@+import { Keyv } from 'keyv';import mongoose from 'mongoose';import { MongoMemoryServer } from 'mongodb-memory-server';import { ResourceType, PrincipalType } from 'librechat-data-provider';@@ -6,13 +7,24 @@ import {createMethods,tenantStorage,createSkillDeletionPersistenceAdapter,+ logger,} from '@librechat/data-schemas';import type { AppConfig } from '@librechat/data-schemas';import type { CheckpointDeletion } from '~/agents/checkpoints/deletion';-import type { UserErasureDeps } from './erasure';+import type { UserErasureDeps, MCPOAuthErasureHooks } from './erasure';+import type { MCPOAuthTokens } from '~/mcp/oauth/types';+import { MCPOAuthHandler, MCPTokenStorage, getMCPOAuthLeaseId } from '~/mcp/oauth';import { deleteAllSharedLinksWithCleanup } from '~/shared-links/service';import { createSkillDeletionService } from '../skills/deletionService';-import { eraseUserData } from './erasure';+import { deleteUserMCPServers, eraseUserData } from './erasure';+import { cleanupMCPServerOAuth } from '~/mcp/oauth/cleanup';+import { FlowStateManager } from '~/flow/manager';++/** Stored OAuth credentials are encrypted with a key read when the module loads. */+jest.mock('@librechat/data-schemas', () => {+ process.env.CREDS_KEY = process.env.CREDS_KEY || 'a'.repeat(64);+ return jest.requireActual('@librechat/data-schemas');+});const OWNER_BITS = 15;@@ -531,3 +543,341 @@ describe('eraseUserData', () => {});}});++describe('removing a shared MCP server with its owner', () => {+ const SERVER_URL = 'https://mcp.example.com/mcp';+ const serverConfig = { type: 'streamable-http' as const, url: SERVER_URL, oauth: {} };++ /** The host teardown the CLI wires, with only the provider's revocation endpoint replaced. */+ function createOAuthHost(+ revokeOAuthToken: jest.Mock,+ deleteTokens: typeof methods.deleteTokens = methods.deleteTokens,+ ) {+ const flowManager = new FlowStateManager<MCPOAuthTokens | null>(new Keyv(), { ttl: 60_000 });+ const uninstallOAuthMCP: MCPOAuthErasureHooks['uninstallOAuthMCP'] = (+ userId,+ pluginKey,+ appConfig,+ config,+ teardown,+ ) =>+ cleanupMCPServerOAuth({+ userId,+ pluginKey,+ appConfig,+ serverConfigOverride: config,+ teardown,+ dependencies: {+ flowManager,+ oauthHandler: {+ generateFlowId: MCPOAuthHandler.generateFlowId.bind(MCPOAuthHandler),+ generateTokenFlowId: MCPOAuthHandler.generateTokenFlowId.bind(MCPOAuthHandler),+ deleteFlowAndStateMapping:+ MCPOAuthHandler.deleteFlowAndStateMapping.bind(MCPOAuthHandler),+ revokeOAuthToken,+ },+ tokenStorage: MCPTokenStorage,+ findToken: methods.findToken,+ deleteTokens,+ getServerConfig: async () => undefined,+ isRegisteredOAuthServer: async () => false,+ },+ });+ return { flowManager, uninstallOAuthMCP };+ }++ async function authorize(userId: mongoose.Types.ObjectId, serverName: string) {+ await MCPTokenStorage.storeTokens({+ userId: userId.toString(),+ serverName,+ tokens: {+ access_token: `access-${userId}`,+ refresh_token: `refresh-${userId}`,+ token_type: 'Bearer',+ expires_in: 3600,+ },+ createToken: methods.createToken,+ updateToken: methods.updateToken,+ findToken: methods.findToken,+ deleteTokens: methods.deleteTokens,+ clientInfo: { client_id: 'shared-client', client_secret: 'shared-secret' },+ metadata: {+ issuer: 'https://auth.example.com',+ authorization_endpoint: 'https://auth.example.com/authorize',+ token_endpoint: 'https://auth.example.com/token',+ revocation_endpoint: 'https://auth.example.com/revoke',+ response_types_supported: ['code'],+ server_url: SERVER_URL,+ client_source: 'dynamic',+ },+ });+ }++ async function share(+ serverId: mongoose.Types.ObjectId,+ ownerId: mongoose.Types.ObjectId,+ principalType: PrincipalType,+ principalId: mongoose.Types.ObjectId,+ ) {+ await methods.grantPermission(+ principalType,+ principalId,+ ResourceType.MCPSERVER,+ serverId,+ 1,+ ownerId,+ );+ }++ function createServerDeps(oauth: MCPOAuthErasureHooks) {+ const { deps } = createDeps();+ return { ...deps, mcpOAuth: oauth };+ }++ it('fences viewers who reach the server through its ACL without an OAuth token', async () => {+ const ownerId = new mongoose.Types.ObjectId();+ const directViewerId = new mongoose.Types.ObjectId();+ const groupViewerId = new mongoose.Types.ObjectId();+ const externalViewerId = new mongoose.Types.ObjectId();+ const outsiderId = new mongoose.Types.ObjectId();+ const { mcpServerId } = await seedUser(ownerId);+ const serverName = `acl-${ownerId}`;+ await model('User').insertMany([+ { _id: groupViewerId, email: `group-${groupViewerId}@example.com` },+ {+ _id: externalViewerId,+ email: `ext-${externalViewerId}@example.com`,+ idOnTheSource: 'entra-1',+ },+ { _id: outsiderId, email: `out-${outsiderId}@example.com` },+ ]);+ const groupId = new mongoose.Types.ObjectId();+ await model('Group').insertOne({+ _id: groupId,+ name: 'Viewers',+ source: 'local',+ memberIds: [groupViewerId.toString(), 'entra-1'],+ });+ await share(mcpServerId, ownerId, PrincipalType.USER, directViewerId);+ await share(mcpServerId, ownerId, PrincipalType.GROUP, groupId);+ const fenced: string[] = [];+ const disconnected: string[] = [];+ const uninstalled: string[] = [];+ const deps = createServerDeps({+ getServerConfig: async () => ({ type: 'streamable-http', url: SERVER_URL }),+ getUserPrincipals: (candidate) => methods.getUserPrincipals({ userId: candidate }),+ resolveAllowlists: async () => ({}),+ invalidateUserTools: async (candidate, fencedServer) => {+ if (fencedServer === serverName) fenced.push(candidate);+ },+ disconnectUser: async (candidate, fencedServer) => {+ if (fencedServer === serverName) disconnected.push(candidate);+ },+ uninstallOAuthMCP: async (candidate, pluginKey) => {+ if (pluginKey === `mcp_${serverName}`) uninstalled.push(candidate);+ },+ });++ await deleteUserMCPServers(ownerId.toString(), deps);++ const expected = [ownerId, directViewerId, groupViewerId, externalViewerId].map(String).sort();+ expect([...new Set(fenced)].sort()).toEqual(expected);+ expect([...new Set(disconnected)].sort()).toEqual(expected);+ expect([...new Set(uninstalled)].sort()).toEqual(expected);+ expect(fenced).not.toContain(outsiderId.toString());+ expect(await count('MCPServer', { _id: mcpServerId })).toBe(0);+ });++ it('removes the server and reports the grant when the provider refuses a revocation', async () => {+ const ownerId = new mongoose.Types.ObjectId();+ const viewerId = new mongoose.Types.ObjectId();+ const { mcpServerId } = await seedUser(ownerId);+ const serverName = `acl-${ownerId}`;+ await share(mcpServerId, ownerId, PrincipalType.USER, viewerId);+ await authorize(viewerId, serverName);+ const revokeOAuthToken = jest.fn().mockRejectedValue(new Error('provider returned 503'));+ const { uninstallOAuthMCP } = createOAuthHost(revokeOAuthToken);+ const deps = createServerDeps({+ getServerConfig: async () => serverConfig,+ getUserPrincipals: (candidate) => methods.getUserPrincipals({ userId: candidate }),+ resolveAllowlists: async () => ({}),+ uninstallOAuthMCP,+ });+ const reported = jest.spyOn(logger, 'error');++ await deleteUserMCPServers(ownerId.toString(), deps);++ expect(revokeOAuthToken.mock.calls.map(([, token, type]) => [token, type])).toEqual([+ [`access-${viewerId}`, 'access'],+ [`refresh-${viewerId}`, 'refresh'],+ ]);+ expect(await count('Token', { userId: viewerId })).toBe(0);+ expect(await count('MCPServer', { _id: mcpServerId })).toBe(0);+ expect(reported).toHaveBeenCalledWith(+ expect.stringContaining(+ `${serverName} did not revoke the access and refresh token of user ${viewerId}`,+ ),+ );+ });++ it('fails closed, keeping the server, when a local token delete fails', async () => {+ const ownerId = new mongoose.Types.ObjectId();+ const viewerId = new mongoose.Types.ObjectId();+ const { mcpServerId } = await seedUser(ownerId);+ const serverName = `acl-${ownerId}`;+ await share(mcpServerId, ownerId, PrincipalType.USER, viewerId);+ await authorize(viewerId, serverName);+ let outage = true;+ const { uninstallOAuthMCP } = createOAuthHost(+ jest.fn().mockResolvedValue(undefined),+ async (query) => {+ if (outage) {+ throw new Error('mongo down');+ }+ return methods.deleteTokens(query);+ },+ );+ const deps = createServerDeps({+ getServerConfig: async () => serverConfig,+ getUserPrincipals: (candidate) => methods.getUserPrincipals({ userId: candidate }),+ resolveAllowlists: async () => ({}),+ uninstallOAuthMCP,+ });++ await expect(deleteUserMCPServers(ownerId.toString(), deps)).rejects.toThrow(+ 'MCP OAuth cleanup failed',+ );+ expect(await count('MCPServer', { _id: mcpServerId })).toBe(1);+ expect(await count('AclEntry', { resourceId: mcpServerId })).toBe(2);+ expect(await count('Token', { userId: viewerId })).toBeGreaterThan(0);++ outage = false;+ await deleteUserMCPServers(ownerId.toString(), deps);+ expect(await count('MCPServer', { _id: mcpServerId })).toBe(0);+ expect(await count('Token', { userId: viewerId })).toBe(0);+ });++ it('holds every OAuth teardown fence until the server delete commits', async () => {+ const ownerId = new mongoose.Types.ObjectId();+ const viewerId = new mongoose.Types.ObjectId();+ const { mcpServerId } = await seedUser(ownerId);+ const serverName = `acl-${ownerId}`;+ await share(mcpServerId, ownerId, PrincipalType.USER, viewerId);+ await authorize(viewerId, serverName);+ const revokeOAuthToken = jest.fn().mockResolvedValue(undefined);+ const { flowManager, uninstallOAuthMCP } = createOAuthHost(revokeOAuthToken);+ const leaseIds = [ownerId, viewerId].map((id) => getMCPOAuthLeaseId(id.toString(), serverName));+ const { deps } = createDeps();+ const duringDelete: Array<number | null> = [];+ const persistedDuringDelete: Array<boolean> = [];+ const deleteMCPServersWithAcl = deps.deleteMCPServersWithAcl;++ await deleteUserMCPServers(ownerId.toString(), {+ ...deps,+ deleteMCPServersWithAcl: async (ids) => {+ for (const leaseId of leaseIds) {+ duringDelete.push(await flowManager.getLeaseGeneration(leaseId));+ }+ /** A callback persisting a new authorization takes the same fence and must not get it. */+ const lease = await flowManager.acquireLease(leaseIds[1], { waitMs: 0 });+ persistedDuringDelete.push(lease != null);+ await lease?.release();+ return deleteMCPServersWithAcl(ids);+ },+ mcpOAuth: {+ getServerConfig: async () => serverConfig,+ getUserPrincipals: (candidate) => methods.getUserPrincipals({ userId: candidate }),+ resolveAllowlists: async () => ({}),+ uninstallOAuthMCP,+ },+ });++ expect(duringDelete).toEqual([null, null]);+ expect(persistedDuringDelete).toEqual([false]);+ expect(await count('MCPServer', { _id: mcpServerId })).toBe(0);+ for (const leaseId of leaseIds) {+ expect(await flowManager.getLeaseGeneration(leaseId)).toEqual(expect.any(Number));+ }+ expect(MCPTokenStorage.isRefreshTeardownActive(viewerId.toString(), serverName)).toBe(false);+ });++ it('keeps the server when a held fence lapsed and another writer took it before the delete', async () => {+ const ownerId = new mongoose.Types.ObjectId();+ const viewerId = new mongoose.Types.ObjectId();+ const { mcpServerId } = await seedUser(ownerId);+ const serverName = `acl-${ownerId}`;+ await share(mcpServerId, ownerId, PrincipalType.USER, viewerId);+ await authorize(viewerId, serverName);+ const { flowManager, uninstallOAuthMCP } = createOAuthHost(+ jest.fn().mockResolvedValue(undefined),+ );+ const viewerLeaseId = getMCPOAuthLeaseId(viewerId.toString(), serverName);+ const deleteMCPServersWithAcl = jest.fn();+ const { deps } = createDeps();+ let lapsed = false;++ await expect(+ deleteUserMCPServers(ownerId.toString(), {+ ...deps,+ deleteMCPServersWithAcl,+ mcpOAuth: {+ getServerConfig: async () => serverConfig,+ getUserPrincipals: (candidate) => methods.getUserPrincipals({ userId: candidate }),+ resolveAllowlists: async () => ({}),+ uninstallOAuthMCP: async (candidate, pluginKey, appConfig, config, teardown) => {+ await uninstallOAuthMCP(candidate, pluginKey, appConfig, config, teardown);+ if (candidate !== viewerId.toString() || lapsed) {+ return;+ }+ /** The viewer's lease outlived its 15 minutes; a callback on another replica took it. */+ lapsed = true;+ const realNow = Date.now();+ const clock = jest.spyOn(Date, 'now').mockReturnValue(realNow + 16 * 60_000);+ try {+ const writer = await flowManager.acquireLease(viewerLeaseId, { waitMs: 0 });+ expect(writer).not.toBeNull();+ await writer?.release();+ } finally {+ clock.mockRestore();+ }+ },+ },+ }),+ ).rejects.toThrow('fence lapsed');++ expect(lapsed).toBe(true);+ expect(deleteMCPServersWithAcl).not.toHaveBeenCalled();+ expect(await count('MCPServer', { _id: mcpServerId })).toBe(1);+ expect(MCPTokenStorage.isRefreshTeardownActive(viewerId.toString(), serverName)).toBe(false);+ });++ it('releases every held fence when a teardown fails locally', async () => {+ const ownerId = new mongoose.Types.ObjectId();+ const viewerId = new mongoose.Types.ObjectId();+ const { mcpServerId } = await seedUser(ownerId);+ const serverName = `acl-${ownerId}`;+ await share(mcpServerId, ownerId, PrincipalType.USER, viewerId);+ await authorize(viewerId, serverName);+ const { flowManager, uninstallOAuthMCP } = createOAuthHost(+ jest.fn().mockResolvedValue(undefined),+ async () => {+ throw new Error('mongo down');+ },+ );+ const deps = createServerDeps({+ getServerConfig: async () => serverConfig,+ getUserPrincipals: (candidate) => methods.getUserPrincipals({ userId: candidate }),+ resolveAllowlists: async () => ({}),+ uninstallOAuthMCP,+ });++ await expect(deleteUserMCPServers(ownerId.toString(), deps)).rejects.toThrow();++ for (const id of [ownerId, viewerId]) {+ const leaseId = getMCPOAuthLeaseId(id.toString(), serverName);+ expect(await flowManager.getLeaseGeneration(leaseId)).toEqual(expect.any(Number));+ expect(MCPTokenStorage.isRefreshTeardownActive(id.toString(), serverName)).toBe(false);+ }+ expect(await count('MCPServer', { _id: mcpServerId })).toBe(1);+ });+});diff --git a/packages/api/src/user/erasure.ts b/packages/api/src/user/erasure.tsindex a1c66e5df3..e6efc581fe 100644--- a/packages/api/src/user/erasure.ts+++ b/packages/api/src/user/erasure.ts@@ -2,9 +2,13 @@ import mongoose from 'mongoose';import { logger } from '@librechat/data-schemas';import type { TCheckpointerConfig, MCPOptions } from 'librechat-data-provider';import type { AllMethods, IMongoFile } from '@librechat/data-schemas';+import type {+ OAuthAclSubject,+ MCPOAuthRetainedFence,+ MCPOAuthTeardownOptions,+} from '../mcp/oauth/cleanup';import type { CheckpointDeletion } from '~/agents/checkpoints/deletion';import type { FileDeletionOutcome } from '../files/deletion';-import type { OAuthAclSubject } from '../mcp/oauth/cleanup';import {cleanupDeletedMCPServerOAuthUsers,prepareMCPServerOAuthDeletion,@@ -35,6 +39,7 @@ type ErasureMethods = Pick<| 'deleteMCPServersWithAcl'| 'findMCPServerOAuthTokenUserIds'| 'findMCPServerViewerEntries'+ | 'findMCPServerViewerUserIds'| 'deleteActions'| 'deleteTokens'| 'removeUserFromAllGroups'@@ -86,6 +91,7 @@ export interface MCPOAuthErasureHooks {mcpSettings?: { allowedDomains?: string[] | null; allowedAddresses?: string[] | null };},serverConfig?: MCPOptions,+ teardown?: MCPOAuthTeardownOptions,) => Promise<void>;}@@ -105,6 +111,7 @@ export type MCPServerCleanupDeps = Pick<| 'disconnectMCPServer'| 'findMCPServerOAuthTokenUserIds'| 'findMCPServerViewerEntries'+ | 'findMCPServerViewerUserIds'| 'mcpOAuth'>;@@ -154,11 +161,15 @@ export async function deleteUserMCPServers(snapshot: await prepareMCPServerOAuthDeletion({getTokenUserIds: () => deps.findMCPServerOAuthTokenUserIds(serverName, tenantId),getAclEntries: () => deps.findMCPServerViewerEntries(id),+ getViewerUserIds: deps.findMCPServerViewerUserIds,}),})),): [];+ /** Each user's OAuth fence stays held until the delete commits, so no authorization or refresh+ * can persist credentials between the cleanup and the removal of the retry anchor. */+ const fences: MCPOAuthRetainedFence[] = [];const cleanupSharedUsers = async (removed: typeof prepared): Promise<number> => {if (!oauth) {return 0;@@ -178,21 +189,47 @@ export async function deleteUserMCPServers(await oauth.disconnectUser?.(candidateId, serverName);},uninstallOAuthMCP: oauth.uninstallOAuthMCP,+ strictRevocation: true,+ retainFence: (fence) => fences.push(fence),}),),);- const failures = results.filter((result) => result.status === 'rejected');- for (const failure of failures) {- logger.error(`[eraseUserData] MCP OAuth cleanup failed for user ${userId}`, failure.reason);- }- return failures.length;+ let failures = 0;+ results.forEach((result, index) => {+ if (result.status === 'rejected') {+ failures++;+ logger.error(`[eraseUserData] MCP OAuth cleanup failed for user ${userId}`, result.reason);+ return;+ }+ /** Local state is gone; the operator needs to know which provider grants may remain. */+ for (const refusal of result.value) {+ logger.error(+ `[eraseUserData] OAuth provider for MCP server ${removed[index].serverName} did not revoke the ${refusal.tokenTypes.join(' and ')} token of user ${refusal.userId}; the external grant may remain valid`,+ );+ }+ });+ return failures;};- /** The server and its ACLs are the retry anchors, so they outlive a failed teardown. */- if ((await cleanupSharedUsers(prepared)) > 0) {- throw new Error('MCP OAuth cleanup failed for users of a server being removed');+ try {+ /** The server and its ACLs are the retry anchors, so they outlive a failed teardown. */+ if ((await cleanupSharedUsers(prepared)) > 0) {+ throw new Error('MCP OAuth cleanup failed for users of a server being removed');+ }+ /** A large teardown can outlive a lease; one that lapsed may have let a writer through. */+ const renewed = await Promise.all(fences.map((fence) => fence.renew()));+ if (renewed.includes(false)) {+ throw new Error('An MCP OAuth teardown fence lapsed before the server was removed');+ }+ await deps.deleteMCPServersWithAcl(servers.map((s) => s.id));+ } finally {+ const releases = await Promise.allSettled(fences.map((fence) => fence.release()));+ for (const result of releases) {+ if (result.status === 'rejected') {+ logger.warn('[eraseUserData] Failed to release an MCP OAuth teardown fence', result.reason);+ }+ }}- await deps.deleteMCPServersWithAcl(servers.map((s) => s.id));}/**diff --git a/packages/api/src/user/resolver.spec.ts b/packages/api/src/user/resolver.spec.tsindex 46b52570e5..be16c9923c 100644--- a/packages/api/src/user/resolver.spec.ts+++ b/packages/api/src/user/resolver.spec.ts@@ -78,8 +78,15 @@ describe('createErasureResolver', () => {userId: 'other-user',serverName: 'srv',});- await erasure.mcpOAuth?.uninstallOAuthMCP('other-user', 'mcp_srv', {});- expect(mcpOAuth.uninstallOAuthMCP).toHaveBeenCalledWith('other-user', 'mcp_srv', {}, undefined);+ const teardown = { strictRevocation: true, retainFence: jest.fn() };+ await erasure.mcpOAuth?.uninstallOAuthMCP('other-user', 'mcp_srv', {}, undefined, teardown);+ expect(mcpOAuth.uninstallOAuthMCP).toHaveBeenCalledWith(+ 'other-user',+ 'mcp_srv',+ {},+ undefined,+ teardown,+ );});it('runs id-keyed lookups in the target tenant, not the calling admin tenant', async () => {@@ -97,6 +104,7 @@ describe('createErasureResolver', () => {deleteUserAgents: jest.fn(record('agents')),findMCPServerOAuthTokenUserIds: jest.fn(record('tokens')),findMCPServerViewerEntries: jest.fn(record('viewers')),+ findMCPServerViewerUserIds: jest.fn(record('viewerUsers')),} as unknown as ErasureResolverDeps['db'],processDeleteRequest: jest.fn(record('files')),invalidateCachedTools: jest.fn(record('fence')),@@ -112,6 +120,7 @@ describe('createErasureResolver', () => {await erasure.deleteUserAgents('user-1');await erasure.findMCPServerOAuthTokenUserIds?.('srv');await erasure.findMCPServerViewerEntries?.('srv-id');+ await erasure.findMCPServerViewerUserIds?.([]);await erasure.deleteStoredFiles([]);await erasure.mcpOAuth?.getServerConfig?.('srv', 'srv-id');await erasure.mcpOAuth?.getUserPrincipals('other');@@ -121,7 +130,7 @@ describe('createErasureResolver', () => {await erasure.mcpOAuth?.disconnectUser?.('other', 'srv');});- expect(Object.keys(seen)).toHaveLength(9);+ expect(Object.keys(seen)).toHaveLength(10);expect(Object.values(seen).every((tenant) => tenant === 'tenant-1')).toBe(true);});diff --git a/packages/api/src/user/resolver.ts b/packages/api/src/user/resolver.tsindex 6f7f8efe8a..c4d918060a 100644--- a/packages/api/src/user/resolver.ts+++ b/packages/api/src/user/resolver.ts@@ -111,6 +111,8 @@ export function createErasureResolver(deps: ErasureResolverDeps) {inTargetTenant(async () => deps.db.findMCPServerOAuthTokenUserIds(serverName)),findMCPServerViewerEntries: (serverId) =>inTargetTenant(async () => deps.db.findMCPServerViewerEntries(serverId)),+ findMCPServerViewerUserIds: (entries) =>+ inTargetTenant(async () => deps.db.findMCPServerViewerUserIds(entries)),deleteStoredFiles: (files) =>inTargetTenant(async () => deps.processDeleteRequest({ req: fileRequest, files })),invalidateMCPServerTools: (serverName) =>@@ -131,9 +133,15 @@ export function createErasureResolver(deps: ErasureResolverDeps) {inTargetTenant(async () =>oauth.getRegistry().resolveAllowlists({ userId: candidateId }),),- uninstallOAuthMCP: (candidateId, pluginKey, cleanupConfig, serverConfig) =>+ uninstallOAuthMCP: (candidateId, pluginKey, cleanupConfig, serverConfig, teardown) =>inTargetTenant(async () =>- oauth.uninstallOAuthMCP(candidateId, pluginKey, cleanupConfig, serverConfig),+ oauth.uninstallOAuthMCP(+ candidateId,+ pluginKey,+ cleanupConfig,+ serverConfig,+ teardown,+ ),),invalidateUserTools: (candidateId, serverName) =>inTargetTenant(async () =>diff --git a/packages/data-schemas/src/methods/mcpServer.spec.ts b/packages/data-schemas/src/methods/mcpServer.spec.tsindex db5b08168d..021c888168 100644--- a/packages/data-schemas/src/methods/mcpServer.spec.ts+++ b/packages/data-schemas/src/methods/mcpServer.spec.ts@@ -12,6 +12,8 @@ import { createMCPServerMethods } from './mcpServer';import { createAclEntryMethods } from './aclEntry';import mcpServerSchema from '~/schema/mcpServer';import aclEntrySchema from '~/schema/aclEntry';+import groupSchema from '~/schema/group';+import userSchema from '~/schema/user';let mongoServer: MongoMemoryServer;let MCPServer: mongoose.Model<t.MCPServerDocument>;@@ -24,6 +26,12 @@ beforeAll(async () => {if (!mongoose.models.AclEntry) {mongoose.model('AclEntry', aclEntrySchema);}+ if (!mongoose.models.Group) {+ mongoose.model('Group', groupSchema);+ }+ if (!mongoose.models.User) {+ mongoose.model('User', userSchema);+ }methods = createMCPServerMethods(mongoose, {getSoleOwnedResourceIds: createAclEntryMethods(mongoose).getSoleOwnedResourceIds,});@@ -659,6 +667,36 @@ describe('MCPServer Model Tests', () => {});});+ describe('findMCPServerViewerUserIds', () => {+ test('expands direct and group viewers to user ids, external members by source id', async () => {+ const directId = new mongoose.Types.ObjectId();+ const localMemberId = new mongoose.Types.ObjectId();+ const externalMemberId = new mongoose.Types.ObjectId();+ const groupId = new mongoose.Types.ObjectId();+ await mongoose.model('User').collection.insertMany([+ { _id: localMemberId, email: '[email protected]' },+ { _id: externalMemberId, email: '[email protected]', idOnTheSource: 'entra-7' },+ ]);+ await mongoose.model('Group').collection.insertOne({+ _id: groupId,+ name: 'Viewers',+ source: 'local',+ memberIds: [localMemberId.toString(), 'entra-7', 'entra-unknown'],+ });++ const userIds = await methods.findMCPServerViewerUserIds([+ { principalType: PrincipalType.USER, principalId: directId },+ { principalType: PrincipalType.GROUP, principalId: groupId.toString() },+ { principalType: PrincipalType.ROLE, principalId: 'USER' },+ { principalType: PrincipalType.PUBLIC },+ ]);++ expect(userIds.sort()).toEqual(+ [directId, localMemberId, externalMemberId].map(String).sort(),+ );+ });+ });+describe('getListMCPServersByNames', () => {test('should return empty data for empty names array', async () => {const result = await methods.getListMCPServersByNames({ names: [] });diff --git a/packages/data-schemas/src/methods/mcpServer.ts b/packages/data-schemas/src/methods/mcpServer.tsindex bd83296503..cfcd012f3f 100644--- a/packages/data-schemas/src/methods/mcpServer.ts+++ b/packages/data-schemas/src/methods/mcpServer.ts@@ -1,5 +1,10 @@import { nanoid } from 'nanoid';-import { ResourceType, PermissionBits, normalizeServerName } from 'librechat-data-provider';+import {+ ResourceType,+ PrincipalType,+ PermissionBits,+ normalizeServerName,+} from 'librechat-data-provider';import type { Model, RootFilterQuery, Types } from 'mongoose';import type { MCPOptions } from 'librechat-data-provider';import type { MCPServerDocument } from '../types';@@ -60,6 +65,14 @@ export interface MCPServerViewerEntry {principalId?: string;}+/** A view-ACL principal as stored or as already read by a caller. */+export interface MCPServerViewerPrincipal {+ principalType: string;+ principalId?: { toString(): string } | string | null;+}++const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i;+export interface ErasableMCPServer {id: string;serverName: string;@@ -103,6 +116,7 @@ export function createMCPServerMethods(deleteMCPServersWithAcl: (ids: string[]) => Promise<number>;findMCPServerOAuthTokenUserIds: (serverName: string, tenantId?: string) => Promise<string[]>;findMCPServerViewerEntries: (serverId: string) => Promise<MCPServerViewerEntry[]>;+ findMCPServerViewerUserIds: (entries: MCPServerViewerPrincipal[]) => Promise<string[]>;} {/*** Finds the next available server name by checking DB and reserved-name collisions.@@ -454,6 +468,59 @@ export function createMCPServerMethods(}));}+ /**+ * Users a server's view ACL names directly or through a group, so its removal can fence viewers+ * who hold no OAuth credential. Role and public principals are not enumerated.+ */+ async function findMCPServerViewerUserIds(+ entries: MCPServerViewerPrincipal[],+ ): Promise<string[]> {+ const userIds = new Set<string>();+ const groupIds = new Set<string>();+ for (const entry of entries) {+ const principalId = entry.principalId?.toString();+ if (!principalId) {+ continue;+ }+ if (entry.principalType === PrincipalType.USER) {+ userIds.add(principalId);+ } else if (+ entry.principalType === PrincipalType.GROUP &&+ OBJECT_ID_PATTERN.test(principalId)+ ) {+ groupIds.add(principalId);+ }+ }+ if (groupIds.size === 0) {+ return [...userIds];+ }+ const groups = await mongoose.models.Group.find({+ _id: { $in: [...groupIds].map((id) => new mongoose.Types.ObjectId(id)) },+ })+ .select('memberIds')+ .lean<Array<{ memberIds?: string[] }>>();+ /** `memberIds` holds `idOnTheSource` for external users and the user id otherwise. */+ const memberIds = [...new Set(groups.flatMap((group) => group.memberIds ?? []))];+ if (memberIds.length === 0) {+ return [...userIds];+ }+ const objectIds = memberIds+ .filter((id) => OBJECT_ID_PATTERN.test(id))+ .map((id) => new mongoose.Types.ObjectId(id));+ const members = await mongoose.models.User.find({+ $or: [+ { idOnTheSource: { $in: memberIds } },+ ...(objectIds.length > 0 ? [{ _id: { $in: objectIds } }] : []),+ ],+ })+ .select('_id')+ .lean<Array<{ _id: Types.ObjectId }>>();+ for (const member of members) {+ userIds.add(member._id.toString());+ }+ return [...userIds];+ }+/** Deletes MCP servers by id together with every ACL entry on them. */async function deleteMCPServersWithAcl(ids: string[]): Promise<number> {if (ids.length === 0) {@@ -475,6 +542,7 @@ export function createMCPServerMethods(deleteMCPServersWithAcl,findMCPServerOAuthTokenUserIds,findMCPServerViewerEntries,+ findMCPServerViewerUserIds,createMCPServer,findMCPServerByServerName,findMCPServerByObjectId,