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: Filter ACL Principal Details (#13524)
Danny Avilac374d08b6425
diff --git a/api/server/controllers/PermissionsController.js b/api/server/controllers/PermissionsController.jsindex 000bba7671..076de31cf3 100644--- a/api/server/controllers/PermissionsController.js+++ b/api/server/controllers/PermissionsController.js@@ -3,7 +3,7 @@*/const mongoose = require('mongoose');-const { logger } = require('@librechat/data-schemas');+const { logger, getTenantId, SYSTEM_TENANT_ID } = require('@librechat/data-schemas');const { ResourceType, PrincipalType, PermissionBits } = require('librechat-data-provider');const { enrichRemoteAgentPrincipals, backfillRemoteAgentPermissions } = require('@librechat/api');const {@@ -21,6 +21,13 @@ const {} = require('~/server/services/GraphApiService');const db = require('~/models');+const matchesCurrentTenant = (principal, tenantId) => {+ if (!tenantId || tenantId === SYSTEM_TENANT_ID) {+ return true;+ }+ return principal?.tenantId === tenantId;+};+/*** Generic controller for resource permission endpoints* Delegates validation and logic to PermissionService@@ -191,6 +198,7 @@ const getResourcePermissions = async (req, res) => {try {const { resourceType, resourceId } = req.params;validateResourceType(resourceType);+ const tenantId = getTenantId();const results = await db.aggregateAclEntries([// Match ACL entries for this resource@@ -244,14 +252,17 @@ const getResourcePermissions = async (req, res) => {let principals = [];let publicPermission = null;- // Process aggregation resultsfor (const result of results) {if (result.principalType === PrincipalType.PUBLIC) {publicPermission = {public: true,publicAccessRoleId: result.accessRoleId,};- } else if (result.principalType === PrincipalType.USER && result.userInfo) {+ } else if (+ result.principalType === PrincipalType.USER &&+ result.userInfo &&+ matchesCurrentTenant(result.userInfo, tenantId)+ ) {principals.push({type: PrincipalType.USER,id: result.userInfo._id.toString(),@@ -262,7 +273,11 @@ const getResourcePermissions = async (req, res) => {idOnTheSource: result.userInfo.idOnTheSource || result.userInfo._id.toString(),accessRoleId: result.accessRoleId,});- } else if (result.principalType === PrincipalType.GROUP && result.groupInfo) {+ } else if (+ result.principalType === PrincipalType.GROUP &&+ result.groupInfo &&+ matchesCurrentTenant(result.groupInfo, tenantId)+ ) {principals.push({type: PrincipalType.GROUP,id: result.groupInfo._id.toString(),diff --git a/api/server/controllers/__tests__/PermissionsController.spec.js b/api/server/controllers/__tests__/PermissionsController.spec.jsindex 6c42ccc59b..5976f9b29a 100644--- a/api/server/controllers/__tests__/PermissionsController.spec.js+++ b/api/server/controllers/__tests__/PermissionsController.spec.js@@ -1,12 +1,16 @@const mongoose = require('mongoose');const mockLogger = { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() };+const mockGetTenantId = jest.fn();jest.mock('@librechat/data-schemas', () => ({logger: mockLogger,+ getTenantId: mockGetTenantId,+ SYSTEM_TENANT_ID: '__SYSTEM__',}));-const { ResourceType, PrincipalType } = jest.requireActual('librechat-data-provider');+const { AccessRoleIds, ResourceType, PrincipalType } =+ jest.requireActual('librechat-data-provider');jest.mock('librechat-data-provider', () => ({...jest.requireActual('librechat-data-provider'),@@ -32,6 +36,7 @@ jest.mock('~/server/services/PermissionService', () => ({const mockRemoveAgentFromUserFavorites = jest.fn();jest.mock('~/models', () => ({+ aggregateAclEntries: jest.fn(),searchPrincipals: jest.fn(),sortPrincipalsByRelevance: jest.fn(),calculateRelevanceScore: jest.fn(),@@ -44,7 +49,11 @@ jest.mock('~/server/services/GraphApiService', () => ({}));const db = require('~/models');-const { updateResourcePermissions, searchPrincipals } = require('../PermissionsController');+const {+ updateResourcePermissions,+ searchPrincipals,+ getResourcePermissions,+} = require('../PermissionsController');const createMockReq = (overrides = {}) => ({params: { resourceType: ResourceType.AGENT, resourceId: '507f1f77bcf86cd799439011' },@@ -66,6 +75,7 @@ const flushPromises = () => new Promise((resolve) => setImmediate(resolve));describe('PermissionsController', () => {beforeEach(() => {jest.clearAllMocks();+ mockGetTenantId.mockReturnValue(undefined);});describe('searchPrincipals', () => {@@ -139,6 +149,108 @@ describe('PermissionsController', () => {});});+ describe('getResourcePermissions — principal details', () => {+ const currentTenantId = 'tenant-a';+ const otherTenantId = 'tenant-b';+ const userId = new mongoose.Types.ObjectId();+ const groupId = new mongoose.Types.ObjectId();++ it('omits joined user and group details outside the current request context', async () => {+ mockGetTenantId.mockReturnValue(currentTenantId);+ db.aggregateAclEntries.mockResolvedValue([+ {+ principalType: PrincipalType.USER,+ accessRoleId: AccessRoleIds.AGENT_VIEWER,+ userInfo: {+ _id: userId,+ tenantId: otherTenantId,+ name: 'Outside User',+ email: '[email protected]',+ avatar: 'outside-user.png',+ },+ },+ {+ principalType: PrincipalType.GROUP,+ accessRoleId: AccessRoleIds.AGENT_VIEWER,+ groupInfo: {+ _id: groupId,+ tenantId: otherTenantId,+ name: 'Outside Group',+ email: '[email protected]',+ avatar: 'outside-group.png',+ },+ },+ {+ principalType: PrincipalType.PUBLIC,+ accessRoleId: AccessRoleIds.AGENT_VIEWER,+ },+ ]);++ const req = createMockReq();+ const res = createMockRes();++ await getResourcePermissions(req, res);++ expect(res.status).toHaveBeenCalledWith(200);+ expect(res.json).toHaveBeenCalledWith({+ resourceType: ResourceType.AGENT,+ resourceId: req.params.resourceId,+ principals: [],+ public: true,+ publicAccessRoleId: AccessRoleIds.AGENT_VIEWER,+ });+ expect(JSON.stringify(res.json.mock.calls[0][0])).not.toContain('[email protected]');+ expect(JSON.stringify(res.json.mock.calls[0][0])).not.toContain('[email protected]');+ });++ it('includes joined user and group details in the current request context', async () => {+ mockGetTenantId.mockReturnValue(currentTenantId);+ db.aggregateAclEntries.mockResolvedValue([+ {+ principalType: PrincipalType.USER,+ accessRoleId: AccessRoleIds.AGENT_VIEWER,+ userInfo: {+ _id: userId,+ tenantId: currentTenantId,+ name: 'Current User',+ email: '[email protected]',+ avatar: 'current-user.png',+ },+ },+ {+ principalType: PrincipalType.GROUP,+ accessRoleId: AccessRoleIds.AGENT_VIEWER,+ groupInfo: {+ _id: groupId,+ tenantId: currentTenantId,+ name: 'Current Group',+ email: '[email protected]',+ avatar: 'current-group.png',+ },+ },+ ]);++ const req = createMockReq();+ const res = createMockRes();++ await getResourcePermissions(req, res);++ expect(res.status).toHaveBeenCalledWith(200);+ expect(res.json.mock.calls[0][0].principals).toEqual([+ expect.objectContaining({+ type: PrincipalType.USER,+ id: userId.toString(),+ email: '[email protected]',+ }),+ expect.objectContaining({+ type: PrincipalType.GROUP,+ id: groupId.toString(),+ email: '[email protected]',+ }),+ ]);+ });+ });+describe('updateResourcePermissions — favorites cleanup', () => {const agentObjectId = new mongoose.Types.ObjectId().toString();const revokedUserId = new mongoose.Types.ObjectId().toString();diff --git a/api/server/services/PermissionService.js b/api/server/services/PermissionService.jsindex 9d40564127..65336ab002 100644--- a/api/server/services/PermissionService.js+++ b/api/server/services/PermissionService.js@@ -27,6 +27,22 @@ const validateResourceType = (resourceType) => {}};+const ensureLocalUserPrincipalExists = async (principalId) => {+ const user = await db.findUser({ _id: principalId }, '_id');+ if (!user) {+ throw new Error('User principal not found');+ }+ return user._id.toString();+};++const ensureLocalGroupPrincipalExists = async (principalId) => {+ const group = await db.findGroupById(principalId, { _id: 1 });+ if (!group) {+ throw new Error('Group principal not found');+ }+ return group._id.toString();+};+/*** @import { TPrincipal } from 'librechat-data-provider'*/@@ -300,8 +316,8 @@ const ensurePrincipalExists = async function (principal) {return null;}- if (principal.id) {- return principal.id;+ if (principal.type === PrincipalType.USER && principal.id) {+ return await ensureLocalUserPrincipalExists(principal.id);}if (principal.type === PrincipalType.USER && principal.source === 'entra') {@@ -366,6 +382,10 @@ const ensureGroupPrincipalExists = async function (principal, authContext = nullthrow new Error(`Invalid principal type: ${principal.type}. Expected '${PrincipalType.GROUP}'`);}+ if (principal.id && principal.source !== 'entra') {+ return await ensureLocalGroupPrincipalExists(principal.id);+ }+if (principal.source === 'entra') {if (!principal.name || !principal.idOnTheSource) {throw new Error('Entra ID group principals must have name and idOnTheSource');diff --git a/api/server/services/PermissionService.spec.js b/api/server/services/PermissionService.spec.jsindex 3fcda2a840..d6f78414a8 100644--- a/api/server/services/PermissionService.spec.js+++ b/api/server/services/PermissionService.spec.js@@ -1,5 +1,5 @@const mongoose = require('mongoose');-const { RoleBits, createModels } = require('@librechat/data-schemas');+const { RoleBits, createModels, tenantStorage } = require('@librechat/data-schemas');const { MongoMemoryServer } = require('mongodb-memory-server');const {ResourceType,@@ -15,6 +15,8 @@ const {getAvailableRoles,grantPermission,checkPermission,+ ensurePrincipalExists,+ ensureGroupPrincipalExists,} = require('./PermissionService');const { findRoleByIdentifier, getUserPrincipals, seedDefaultRoles } = require('~/models');@@ -44,6 +46,8 @@ jest.mock('~/config', () => ({let mongoServer;let AclEntry;+let User;+let Group;beforeAll(async () => {mongoServer = await MongoMemoryServer.create();@@ -58,6 +62,8 @@ beforeAll(async () => {Object.assign(mongoose.models, dbModels);AclEntry = dbModels.AclEntry;+ User = dbModels.User;+ Group = dbModels.Group;// Seed default rolesawait seedDefaultRoles();@@ -243,6 +249,69 @@ describe('PermissionService', () => {});});+ describe('principal validation for ACL writes', () => {+ beforeEach(async () => {+ await User.deleteMany({ email: /acl-principal/i });+ await Group.deleteMany({ name: /ACL Principal/i });+ });++ test('rejects a local user id outside the current request context', async () => {+ const outsideUser = await User.create({+ name: 'ACL Principal Outside User',+ email: '[email protected]',+ tenantId: 'tenant-b',+ });++ await expect(+ tenantStorage.run({ tenantId: 'tenant-a' }, async () =>+ ensurePrincipalExists({+ type: PrincipalType.USER,+ id: outsideUser._id.toString(),+ name: 'Outside User',+ source: 'local',+ }),+ ),+ ).rejects.toThrow('User principal not found');+ });++ test('accepts a local user id in the current request context', async () => {+ const currentUser = await User.create({+ name: 'ACL Principal Current User',+ email: '[email protected]',+ tenantId: 'tenant-a',+ });++ const principalId = await tenantStorage.run({ tenantId: 'tenant-a' }, async () =>+ ensurePrincipalExists({+ type: PrincipalType.USER,+ id: currentUser._id.toString(),+ name: 'Current User',+ source: 'local',+ }),+ );++ expect(principalId).toBe(currentUser._id.toString());+ });++ test('rejects a local group id outside the current request context', async () => {+ const outsideGroup = await Group.create({+ name: 'ACL Principal Outside Group',+ tenantId: 'tenant-b',+ });++ await expect(+ tenantStorage.run({ tenantId: 'tenant-a' }, async () =>+ ensureGroupPrincipalExists({+ type: PrincipalType.GROUP,+ id: outsideGroup._id.toString(),+ name: 'Outside Group',+ source: 'local',+ }),+ ),+ ).rejects.toThrow('Group principal not found');+ });+ });+describe('checkPermission', () => {let otherResourceId;diff --git a/e2e/specs/mock/permissions.spec.ts b/e2e/specs/mock/permissions.spec.tsnew file mode 100644index 0000000000..ae02995c32--- /dev/null+++ b/e2e/specs/mock/permissions.spec.ts@@ -0,0 +1,407 @@+import { expect, request as playwrightRequest, test } from '@playwright/test';+import { MongoClient, ObjectId } from 'mongodb';+import type { APIRequestContext } from '@playwright/test';+import type { Collection, Db } from 'mongodb';+import cleanupUser from '../../setup/cleanupUser';+import { applyRuntimeEnv } from '../../setup/runtimeEnv';++type TestUser = {+ email: string;+ name: string;+ password: string;+};++type UserDoc = {+ _id: ObjectId;+ email: string;+ name: string;+ tenantId?: string;+};++type GroupDoc = {+ _id: ObjectId;+ name: string;+ email?: string;+ tenantId?: string;+};++type AccessRoleDoc = {+ _id: ObjectId;+ accessRoleId: string;+ resourceType: string;+ permBits: number;+ tenantId?: string;+};++type PrincipalResponse = {+ type: string;+ id: string;+ email?: string;+ name?: string;+ accessRoleId: string;+};++type PermissionsResponse = {+ principals: PrincipalResponse[];+};++type AuthenticatedRequest = {+ api: APIRequestContext;+ token: string;+ role: string;+};++const CURRENT_TENANT_ID = 'e2e-acl-current';+const OTHER_TENANT_ID = 'e2e-acl-other';+const RESOURCE_TYPE_AGENT = 'agent';+const PRINCIPAL_TYPE_USER = 'user';+const PRINCIPAL_TYPE_GROUP = 'group';+const PRINCIPAL_MODEL_USER = 'User';+const PRINCIPAL_MODEL_GROUP = 'Group';+const ACCESS_ROLE_AGENT_OWNER = 'agent_owner';+const ACCESS_ROLE_AGENT_VIEWER = 'agent_viewer';+const PERM_BITS_VIEWER = 1;+const PERM_BITS_OWNER = 15;++const randomSuffix = () => `${Date.now()}-${Math.floor(Math.random() * 10000)}`;++async function connectToE2EDb() {+ applyRuntimeEnv();+ if (!process.env.MONGO_URI) {+ throw new Error('MONGO_URI must be available for permissions mock e2e tests');+ }++ const client = new MongoClient(process.env.MONGO_URI);+ await client.connect();+ return { client, db: client.db() };+}++async function createAuthenticatedRequest(+ baseURL: string,+ user: TestUser,+ tenantId: string,+): Promise<AuthenticatedRequest> {+ await cleanupUser(user);++ const api = await playwrightRequest.newContext({+ baseURL,+ storageState: { cookies: [], origins: [] },+ extraHTTPHeaders: {+ 'X-Tenant-Id': tenantId,+ },+ });++ const registerResponse = await api.post('/api/auth/register', {+ data: {+ email: user.email,+ name: user.name,+ password: user.password,+ confirm_password: user.password,+ },+ });+ expect(registerResponse.ok()).toBeTruthy();++ const loginResponse = await api.post('/api/auth/login', {+ data: {+ email: user.email,+ password: user.password,+ },+ });+ expect(loginResponse.ok()).toBeTruthy();+ const loginPayload = (await loginResponse.json()) as { token?: string; user?: { role?: string } };+ if (!loginPayload.token || !loginPayload.user?.role) {+ throw new Error('Expected login response to include a bearer token and user role');+ }++ return {+ api,+ token: loginPayload.token,+ role: loginPayload.user.role,+ };+}++async function seedTenantRole(db: Db, tenantId: string, roleName: string) {+ await db.collection('roles').updateOne(+ { name: roleName, tenantId },+ {+ $set: {+ name: roleName,+ tenantId,+ permissions: {+ AGENTS: {+ USE: true,+ CREATE: true,+ SHARE: true,+ SHARE_PUBLIC: true,+ },+ },+ },+ $setOnInsert: {+ createdAt: new Date(),+ },+ $currentDate: {+ updatedAt: true,+ },+ },+ { upsert: true },+ );+}++async function seedAccessRole(+ accessRoles: Collection<AccessRoleDoc>,+ tenantId: string,+ accessRoleId: string,+ permBits: number,+): Promise<AccessRoleDoc> {+ await accessRoles.updateOne(+ { accessRoleId, tenantId },+ {+ $set: {+ accessRoleId,+ tenantId,+ resourceType: RESOURCE_TYPE_AGENT,+ permBits,+ name: accessRoleId,+ },+ $setOnInsert: {+ createdAt: new Date(),+ },+ $currentDate: {+ updatedAt: true,+ },+ },+ { upsert: true },+ );++ const role = await accessRoles.findOne({ accessRoleId, tenantId });+ if (!role) {+ throw new Error(`Expected seeded access role ${accessRoleId}`);+ }+ return role;+}++test.describe('permission principal details', () => {+ test.setTimeout(120000);++ test('keeps permission details and local principal writes in the authenticated context', async ({+ baseURL,+ }) => {+ if (typeof baseURL !== 'string') {+ throw new Error('baseURL must be configured for permissions mock e2e tests');+ }++ const suffix = randomSuffix();+ const ownerUser: TestUser = {+ email: `acl-owner-${suffix}@example.com`,+ name: `ACL Owner ${suffix}`,+ password: 'securepassword123',+ };++ const { api, role, token } = await createAuthenticatedRequest(+ baseURL,+ ownerUser,+ CURRENT_TENANT_ID,+ );+ const { client, db } = await connectToE2EDb();+ const users = db.collection<UserDoc>('users');+ const groups = db.collection<GroupDoc>('groups');+ const aclEntries = db.collection('aclentries');+ const accessRoles = db.collection<AccessRoleDoc>('accessroles');+ const resourceId = new ObjectId();+ const createdIds: ObjectId[] = [];++ try {+ await seedTenantRole(db, CURRENT_TENANT_ID, role);+ const ownerRole = await seedAccessRole(+ accessRoles,+ CURRENT_TENANT_ID,+ ACCESS_ROLE_AGENT_OWNER,+ PERM_BITS_OWNER,+ );+ const viewerRole = await seedAccessRole(+ accessRoles,+ CURRENT_TENANT_ID,+ ACCESS_ROLE_AGENT_VIEWER,+ PERM_BITS_VIEWER,+ );++ const currentOwner = await users.findOne({+ email: ownerUser.email,+ tenantId: CURRENT_TENANT_ID,+ });+ if (!currentOwner) {+ throw new Error('Expected authenticated e2e user to be stored with a tenant id');+ }++ const outsideUserId = new ObjectId();+ const outsideGroupId = new ObjectId();+ const outsideWriteUserId = new ObjectId();+ const currentGroupId = new ObjectId();+ createdIds.push(outsideUserId, outsideGroupId, outsideWriteUserId, currentGroupId);++ await users.insertMany([+ {+ _id: outsideUserId,+ email: `outside-read-${suffix}@example.com`,+ name: `Outside Read User ${suffix}`,+ tenantId: OTHER_TENANT_ID,+ },+ {+ _id: outsideWriteUserId,+ email: `outside-write-${suffix}@example.com`,+ name: `Outside Write User ${suffix}`,+ tenantId: OTHER_TENANT_ID,+ },+ ]);+ await groups.insertMany([+ {+ _id: outsideGroupId,+ email: `outside-group-${suffix}@example.com`,+ name: `Outside Group ${suffix}`,+ tenantId: OTHER_TENANT_ID,+ },+ {+ _id: currentGroupId,+ email: `current-group-${suffix}@example.com`,+ name: `Current Group ${suffix}`,+ tenantId: CURRENT_TENANT_ID,+ },+ ]);++ await aclEntries.insertMany([+ {+ principalType: PRINCIPAL_TYPE_USER,+ principalId: currentOwner._id,+ principalModel: PRINCIPAL_MODEL_USER,+ resourceType: RESOURCE_TYPE_AGENT,+ resourceId,+ permBits: ownerRole.permBits,+ roleId: ownerRole._id,+ grantedBy: currentOwner._id,+ tenantId: CURRENT_TENANT_ID,+ createdAt: new Date(),+ updatedAt: new Date(),+ },+ {+ principalType: PRINCIPAL_TYPE_USER,+ principalId: outsideUserId,+ principalModel: PRINCIPAL_MODEL_USER,+ resourceType: RESOURCE_TYPE_AGENT,+ resourceId,+ permBits: viewerRole.permBits,+ roleId: viewerRole._id,+ grantedBy: currentOwner._id,+ tenantId: CURRENT_TENANT_ID,+ createdAt: new Date(),+ updatedAt: new Date(),+ },+ {+ principalType: PRINCIPAL_TYPE_GROUP,+ principalId: outsideGroupId,+ principalModel: PRINCIPAL_MODEL_GROUP,+ resourceType: RESOURCE_TYPE_AGENT,+ resourceId,+ permBits: viewerRole.permBits,+ roleId: viewerRole._id,+ grantedBy: currentOwner._id,+ tenantId: CURRENT_TENANT_ID,+ createdAt: new Date(),+ updatedAt: new Date(),+ },+ ]);++ const authHeaders = { Authorization: `Bearer ${token}` };++ const getResponse = await api.get(`/api/permissions/${RESOURCE_TYPE_AGENT}/${resourceId}`, {+ headers: authHeaders,+ });+ expect(getResponse.ok()).toBeTruthy();+ const getPayload = (await getResponse.json()) as PermissionsResponse;+ const serializedGetPayload = JSON.stringify(getPayload);++ expect(getPayload.principals).toEqual([+ expect.objectContaining({+ type: PRINCIPAL_TYPE_USER,+ id: currentOwner._id.toString(),+ email: ownerUser.email,+ accessRoleId: ACCESS_ROLE_AGENT_OWNER,+ }),+ ]);+ expect(serializedGetPayload).not.toContain(`outside-read-${suffix}@example.com`);+ expect(serializedGetPayload).not.toContain(`outside-group-${suffix}@example.com`);+ expect(serializedGetPayload).not.toContain(outsideUserId.toString());+ expect(serializedGetPayload).not.toContain(outsideGroupId.toString());++ const putResponse = await api.put(`/api/permissions/${RESOURCE_TYPE_AGENT}/${resourceId}`, {+ headers: authHeaders,+ data: {+ updated: [+ {+ type: PRINCIPAL_TYPE_GROUP,+ id: currentGroupId.toString(),+ name: `Current Group ${suffix}`,+ source: 'local',+ accessRoleId: ACCESS_ROLE_AGENT_VIEWER,+ },+ {+ type: PRINCIPAL_TYPE_USER,+ id: outsideWriteUserId.toString(),+ name: `Outside Write User ${suffix}`,+ email: `outside-write-${suffix}@example.com`,+ source: 'local',+ accessRoleId: ACCESS_ROLE_AGENT_VIEWER,+ },+ ],+ removed: [],+ },+ });+ expect(putResponse.ok()).toBeTruthy();+ const putPayload = (await putResponse.json()) as { results: PermissionsResponse };+ const serializedPutPayload = JSON.stringify(putPayload);++ expect(putPayload.results.principals).toEqual([+ expect.objectContaining({+ type: PRINCIPAL_TYPE_GROUP,+ id: currentGroupId.toString(),+ accessRoleId: ACCESS_ROLE_AGENT_VIEWER,+ }),+ ]);+ expect(serializedPutPayload).not.toContain(outsideWriteUserId.toString());+ expect(serializedPutPayload).not.toContain(`outside-write-${suffix}@example.com`);+ await expect+ .poll(() =>+ aclEntries.countDocuments({+ resourceType: RESOURCE_TYPE_AGENT,+ resourceId,+ principalId: currentGroupId,+ tenantId: CURRENT_TENANT_ID,+ }),+ )+ .toBe(1);+ await expect+ .poll(() =>+ aclEntries.countDocuments({+ resourceType: RESOURCE_TYPE_AGENT,+ resourceId,+ principalId: outsideWriteUserId,+ tenantId: CURRENT_TENANT_ID,+ }),+ )+ .toBe(0);+ } finally {+ await Promise.all([+ aclEntries.deleteMany({ resourceId }),+ users.deleteMany({ _id: { $in: createdIds } }),+ groups.deleteMany({ _id: { $in: createdIds } }),+ db.collection('roles').deleteOne({ name: role, tenantId: CURRENT_TENANT_ID }),+ accessRoles.deleteMany({+ accessRoleId: { $in: [ACCESS_ROLE_AGENT_OWNER, ACCESS_ROLE_AGENT_VIEWER] },+ tenantId: CURRENT_TENANT_ID,+ }),+ ]);+ await client.close();+ await api.dispose();+ await cleanupUser(ownerUser);+ }+ });+});diff --git a/packages/api/src/apiKeys/permissions.spec.ts b/packages/api/src/apiKeys/permissions.spec.tsindex 69441fa800..bcf6f642f7 100644--- a/packages/api/src/apiKeys/permissions.spec.ts+++ b/packages/api/src/apiKeys/permissions.spec.ts@@ -5,7 +5,7 @@ import {PermissionBits,AccessRoleIds,} from 'librechat-data-provider';-import { permissionBitSupersets } from '@librechat/data-schemas';+import { permissionBitSupersets, tenantStorage } from '@librechat/data-schemas';import { enrichRemoteAgentPrincipals } from './permissions';import type { EnricherDependencies, Principal } from './permissions';@@ -57,8 +57,8 @@ describe('enrichRemoteAgentPrincipals', () => {await enrichRemoteAgentPrincipals(deps, resourceId, []);- const pipeline = aggregateAclEntries.mock.calls[0][0];- const matchStage = pipeline[0].$match;+ const pipeline = aggregateAclEntries.mock.calls[0][0] as Record<string, unknown>[];+ const matchStage = pipeline[0].$match as Record<string, unknown>;expect(matchStage.resourceType).toBe(ResourceType.AGENT);expect(matchStage.principalType).toBe(PrincipalType.USER);expect(matchStage.resourceId).toBeInstanceOf(Types.ObjectId);@@ -100,6 +100,33 @@ describe('enrichRemoteAgentPrincipals', () => {expect(matchStage.resourceId).toBeInstanceOf(Types.ObjectId);expect((matchStage.resourceId as Types.ObjectId).toString()).toBe(hexId);});++ test('keeps the user lookup in simple localField/foreignField form', async () => {+ const aggregateAclEntries = jest.fn().mockResolvedValue([]);+ const deps: EnricherDependencies = {+ aggregateAclEntries,+ bulkWriteAclEntries: jest.fn(),+ findRoleByIdentifier: jest.fn(),+ logger: { error: jest.fn() },+ };++ await enrichRemoteAgentPrincipals(deps, resourceId, []);++ const pipeline = aggregateAclEntries.mock.calls[0][0] as Record<string, unknown>[];+ const lookupStage = pipeline.find((stage) => '$lookup' in stage) as+ | { $lookup: Record<string, unknown> }+ | undefined;+ expect(lookupStage).toMatchObject({+ $lookup: {+ from: 'users',+ localField: 'principalId',+ foreignField: '_id',+ as: 'userInfo',+ },+ });+ expect(lookupStage?.$lookup).not.toHaveProperty('let');+ expect(lookupStage?.$lookup).not.toHaveProperty('pipeline');+ });});describe('enrichment behavior', () => {@@ -136,6 +163,25 @@ describe('enrichRemoteAgentPrincipals', () => {expect(result.entriesToBackfill).toHaveLength(0);});+ test('skips joined userInfo outside the current request context', async () => {+ const deps = makeDeps([+ {+ principalId: ownerUserId,+ userInfo: makeUserInfo(ownerUserId, {+ tenantId: 'tenant-b',+ email: '[email protected]',+ }),+ },+ ]);++ const result = await tenantStorage.run({ tenantId: 'tenant-a' }, async () =>+ enrichRemoteAgentPrincipals(deps, resourceId, []),+ );++ expect(result.principals).toHaveLength(0);+ expect(result.entriesToBackfill).toHaveLength(0);+ });+test('does not duplicate a principal already present in the input list', async () => {const existing: Principal = {type: PrincipalType.USER,diff --git a/packages/api/src/apiKeys/permissions.ts b/packages/api/src/apiKeys/permissions.tsindex 3d8a05b3b9..a64a9f4a51 100644--- a/packages/api/src/apiKeys/permissions.ts+++ b/packages/api/src/apiKeys/permissions.ts@@ -5,7 +5,7 @@ import {PermissionBits,AccessRoleIds,} from 'librechat-data-provider';-import { permissionBitSupersets } from '@librechat/data-schemas';+import { SYSTEM_TENANT_ID, getTenantId, permissionBitSupersets } from '@librechat/data-schemas';import type { PipelineStage, AnyBulkWriteOperation } from 'mongoose';export interface Principal {@@ -37,6 +37,13 @@ export interface EnrichResult {entriesToBackfill: Types.ObjectId[];}+function matchesCurrentTenant(principal: Record<string, unknown>, tenantId?: string): boolean {+ if (!tenantId || tenantId === SYSTEM_TENANT_ID) {+ return true;+ }+ return principal.tenantId === tenantId;+}+/** Enriches REMOTE_AGENT principals with implicit AGENT owners */export async function enrichRemoteAgentPrincipals(deps: EnricherDependencies,@@ -47,6 +54,7 @@ export async function enrichRemoteAgentPrincipals(typeof resourceId === 'string' && /^[a-f\d]{24}$/i.test(resourceId)? Types.ObjectId.createFromHexString(resourceId): resourceId;+ const tenantId = getTenantId();/*** Filter `permBits` with `$in: permissionBitSupersets(SHARE)` instead of@@ -87,6 +95,10 @@ export async function enrichRemoteAgentPrincipals(}const userInfo = entry.userInfo as Record<string, unknown>;+ if (!matchesCurrentTenant(userInfo, tenantId)) {+ continue;+ }+const principalId = entry.principalId as Types.ObjectId;const alreadyIncluded = enrichedPrincipals.some(