mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-03-21 23:26:34 +01:00
🪦 fix: ACL-Safe User Account Deletion for Agents, Prompts, and MCP Servers (#12314)
* fix: use ACL ownership for prompt group cleanup on user deletion deleteUserPrompts previously called getAllPromptGroups with only an author filter, which defaults to searchShared=true and drops the author filter for shared/global project entries. This caused any user deleting their account to strip shared prompt group associations and ACL entries for other users. Replace the author-based query with ACL-based ownership lookup: - Find prompt groups where the user has OWNER permission (DELETE bit) - Only delete groups where the user is the sole owner - Preserve multi-owned groups and their ACL entries for other owners * fix: use ACL ownership for agent cleanup on user deletion deleteUserAgents used the deprecated author field to find and delete agents, then unconditionally removed all ACL entries for those agents. This could destroy ACL entries for agents shared with or co-owned by other users. Replace the author-based query with ACL-based ownership lookup: - Find agents where the user has OWNER permission (DELETE bit) - Only delete agents where the user is the sole owner - Preserve multi-owned agents and their ACL entries for other owners - Also clean up handoff edges referencing deleted agents * fix: add MCP server cleanup on user deletion User deletion had no cleanup for MCP servers, leaving solely-owned servers orphaned in the database with dangling ACL entries for other users. Add deleteUserMcpServers that follows the same ACL ownership pattern as prompt groups and agents: find servers with OWNER permission, check for sole ownership, and only delete those with no other owners. * style: fix prettier formatting in Prompt.spec.js * refactor: extract getSoleOwnedResourceIds to PermissionService The ACL sole-ownership detection algorithm was duplicated across deleteUserPrompts, deleteUserAgents, and deleteUserMcpServers. Centralizes the three-step pattern (find owned entries, find other owners, compute sole-owned set) into a single reusable utility. * refactor: use getSoleOwnedResourceIds in all deletion functions - Replace inline ACL queries with the centralized utility - Remove vestigial _req parameter from deleteUserPrompts - Use Promise.all for parallel project removal instead of sequential awaits - Disconnect live MCP sessions and invalidate tool cache before deleting sole-owned MCP server documents - Export deleteUserMcpServers for testability * test: improve deletion test coverage and quality - Move deleteUserPrompts call to beforeAll to eliminate execution-order dependency between tests - Standardize on test() instead of it() for consistency in Prompt.spec.js - Add assertion for deleting user's own ACL entry preservation on multi-owned agents - Add deleteUserMcpServers integration test suite with 6 tests covering sole-owner deletion, multi-owner preservation, session disconnect, cache invalidation, model-not-registered guard, and missing MCPManager - Add PermissionService mock to existing deleteUser.spec.js to fix import chain * fix: add legacy author-based fallback for unmigrated resources Resources created before the ACL system have author set but no AclEntry records. The sole-ownership detection returns empty for these, causing deleteUserPrompts, deleteUserAgents, and deleteUserMcpServers to silently skip them — permanently orphaning data on user deletion. Add a fallback that identifies author-owned resources with zero ACL entries (truly unmigrated) and includes them in the deletion set. This preserves the multi-owner safety of the ACL path while ensuring pre-ACL resources are still cleaned up regardless of migration status. * style: fix prettier formatting across all changed files * test: add resource type coverage guard for user deletion Ensures every ResourceType in the ACL system has a corresponding cleanup handler wired into deleteUserController. When a new ResourceType is added (e.g. WORKFLOW), this test fails immediately, preventing silent data orphaning on user account deletion. * style: fix import order in PermissionService destructure * test: add opt-out set and fix test lifecycle in coverage guard Add NO_USER_CLEANUP_NEEDED set for resource types that legitimately require no per-user deletion. Move fs.readFileSync into beforeAll so path errors surface as clean test failures instead of unhandled crashes.
This commit is contained in:
parent
f380390408
commit
1ecff83b20
9 changed files with 993 additions and 60 deletions
|
|
@ -1,11 +1,18 @@
|
|||
const mongoose = require('mongoose');
|
||||
const { logger, webSearchKeys } = require('@librechat/data-schemas');
|
||||
const { Tools, CacheKeys, Constants, FileSources } = require('librechat-data-provider');
|
||||
const {
|
||||
MCPOAuthHandler,
|
||||
MCPTokenStorage,
|
||||
normalizeHttpError,
|
||||
extractWebSearchEnvVars,
|
||||
} = require('@librechat/api');
|
||||
const {
|
||||
Tools,
|
||||
CacheKeys,
|
||||
Constants,
|
||||
FileSources,
|
||||
ResourceType,
|
||||
} = require('librechat-data-provider');
|
||||
const {
|
||||
deleteAllUserSessions,
|
||||
deleteAllSharedLinks,
|
||||
|
|
@ -45,6 +52,7 @@ const { getAppConfig } = require('~/server/services/Config');
|
|||
const { deleteToolCalls } = require('~/models/ToolCall');
|
||||
const { deleteUserPrompts } = require('~/models/Prompt');
|
||||
const { deleteUserAgents } = require('~/models/Agent');
|
||||
const { getSoleOwnedResourceIds } = require('~/server/services/PermissionService');
|
||||
const { getLogStores } = require('~/cache');
|
||||
|
||||
const getUserController = async (req, res) => {
|
||||
|
|
@ -113,6 +121,78 @@ const deleteUserFiles = async (req) => {
|
|||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes MCP servers solely owned by the user and cleans up their ACLs.
|
||||
* Disconnects live sessions for deleted servers before removing DB records.
|
||||
* Servers with other owners are left intact; the caller is responsible for
|
||||
* removing the user's own ACL principal entries separately.
|
||||
*
|
||||
* Also handles legacy (pre-ACL) MCP servers that only have the author field set,
|
||||
* ensuring they are not orphaned if no permission migration has been run.
|
||||
* @param {string} userId - The ID of the user.
|
||||
*/
|
||||
const deleteUserMcpServers = async (userId) => {
|
||||
try {
|
||||
const MCPServer = mongoose.models.MCPServer;
|
||||
if (!MCPServer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const userObjectId = new mongoose.Types.ObjectId(userId);
|
||||
const soleOwnedIds = await getSoleOwnedResourceIds(userObjectId, ResourceType.MCPSERVER);
|
||||
|
||||
const authoredServers = await MCPServer.find({ author: userObjectId })
|
||||
.select('_id serverName')
|
||||
.lean();
|
||||
|
||||
const migratedEntries =
|
||||
authoredServers.length > 0
|
||||
? await AclEntry.find({
|
||||
resourceType: ResourceType.MCPSERVER,
|
||||
resourceId: { $in: authoredServers.map((s) => s._id) },
|
||||
})
|
||||
.select('resourceId')
|
||||
.lean()
|
||||
: [];
|
||||
const migratedIds = new Set(migratedEntries.map((e) => e.resourceId.toString()));
|
||||
const legacyServers = authoredServers.filter((s) => !migratedIds.has(s._id.toString()));
|
||||
const legacyServerIds = legacyServers.map((s) => s._id);
|
||||
|
||||
const allServerIdsToDelete = [...soleOwnedIds, ...legacyServerIds];
|
||||
|
||||
if (allServerIdsToDelete.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const aclOwnedServers =
|
||||
soleOwnedIds.length > 0
|
||||
? await MCPServer.find({ _id: { $in: soleOwnedIds } })
|
||||
.select('serverName')
|
||||
.lean()
|
||||
: [];
|
||||
const allServersToDelete = [...aclOwnedServers, ...legacyServers];
|
||||
|
||||
const mcpManager = getMCPManager();
|
||||
if (mcpManager) {
|
||||
await Promise.all(
|
||||
allServersToDelete.map(async (s) => {
|
||||
await mcpManager.disconnectUserConnection(userId, s.serverName);
|
||||
await invalidateCachedTools({ userId, serverName: s.serverName });
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
await AclEntry.deleteMany({
|
||||
resourceType: ResourceType.MCPSERVER,
|
||||
resourceId: { $in: allServerIdsToDelete },
|
||||
});
|
||||
|
||||
await MCPServer.deleteMany({ _id: { $in: allServerIdsToDelete } });
|
||||
} catch (error) {
|
||||
logger.error('[deleteUserMcpServers] General error:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const updateUserPluginsController = async (req, res) => {
|
||||
const appConfig = await getAppConfig({ role: req.user?.role });
|
||||
const { user } = req;
|
||||
|
|
@ -281,7 +361,8 @@ const deleteUserController = async (req, res) => {
|
|||
await Assistant.deleteMany({ user: user.id }); // delete user assistants
|
||||
await ConversationTag.deleteMany({ user: user.id }); // delete user conversation tags
|
||||
await MemoryEntry.deleteMany({ userId: user.id }); // delete user memory entries
|
||||
await deleteUserPrompts(req, user.id); // delete user prompts
|
||||
await deleteUserPrompts(user.id); // delete user prompts
|
||||
await deleteUserMcpServers(user.id); // delete user MCP servers
|
||||
await Action.deleteMany({ user: user.id }); // delete user actions
|
||||
await Token.deleteMany({ userId: user.id }); // delete user OAuth tokens
|
||||
await Group.updateMany(
|
||||
|
|
@ -439,4 +520,5 @@ module.exports = {
|
|||
verifyEmailController,
|
||||
updateUserPluginsController,
|
||||
resendVerificationController,
|
||||
deleteUserMcpServers,
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue