LibreChat/packages/data-schemas/src/methods/aclEntry.spec.ts
“Praneeth 949682ef0f
🏪 feat: Agent Marketplace
bugfix: Enhance Agent and AgentCategory schemas with new fields for category, support contact, and promotion status

refactored and moved agent category methods and schema to data-schema package

🔧 fix: Merge and Rebase Conflicts

- Move AgentCategory from api/models to @packages/data-schemas structure
  - Add schema, types, methods, and model following codebase conventions
  - Implement auto-seeding of default categories during AppService startup
  - Update marketplace controller to use new data-schemas methods
  - Remove old model file and standalone seed script

refactor: unify agent marketplace to single endpoint with cursor pagination

  - Replace multiple marketplace routes with unified /marketplace endpoint
  - Add query string controls: category, search, limit, cursor, promoted, requiredPermission
  - Implement cursor-based pagination replacing page-based system
  - Integrate ACL permissions for proper access control
  - Fix ObjectId constructor error in Agent model
  - Update React components to use unified useGetMarketplaceAgentsQuery hook
  - Enhance type safety and remove deprecated useDynamicAgentQuery
  - Update tests for new marketplace architecture
  -Known issues:
  see more button after category switching + Unit tests

feat: add icon property to ProcessedAgentCategory interface

- Add useMarketplaceAgentsInfiniteQuery and useGetAgentCategoriesQuery to client/src/data-provider/Agents/
  - Replace manual pagination in AgentGrid with infinite query pattern
  - Update imports to use local data provider instead of librechat-data-provider
  - Add proper permission handling with PERMISSION_BITS.VIEW/EDIT constants
  - Improve agent access control by adding requiredPermission validation in backend
  - Remove manual cursor/state management in favor of infinite query built-ins
  - Maintain existing search and category filtering functionality

refactor: consolidate agent marketplace endpoints into main agents API and improve data management consistency

  - Remove dedicated marketplace controller and routes, merging functionality into main agents v1 API
  - Add countPromotedAgents function to Agent model for promoted agents count
  - Enhance getListAgents handler with marketplace filtering (category, search, promoted status)
  - Move getAgentCategories from marketplace to v1 controller with same functionality
  - Update agent mutations to invalidate marketplace queries and handle multiple permission levels
  - Improve cache management by updating all agent query variants (VIEW/EDIT permissions)
  - Consolidate agent data access patterns for better maintainability and consistency
  - Remove duplicate marketplace route definitions and middleware

selected view only agents injected in the drop down

fix: remove minlength validation for support contact name in agent schema

feat: add validation and error messages for agent name in AgentConfig and AgentPanel

fix: update agent permission check logic in AgentPanel to simplify condition

Fix linting WIP

Fix Unit tests WIP

ESLint fixes

eslint fix

refactor: enhance isDuplicateVersion function in Agent model for improved comparison logic

- Introduced handling for undefined/null values in array and object comparisons.
- Normalized array comparisons to treat undefined/null as empty arrays.
- Added deep comparison for objects and improved handling of primitive values.
- Enhanced projectIds comparison to ensure consistent MongoDB ObjectId handling.

refactor: remove redundant properties from IAgent interface in agent schema

chore: update localization for agent detail component and clean up imports

ci: update access middleware tests

chore: remove unused PermissionTypes import from Role model

ci: update AclEntry model tests

ci: update button accessibility labels in AgentDetail tests

refactor: update exhaustive dep. lint warning

🔧 fix: Fixed agent actions access

feat: Add role-level permissions for agent sharing people picker

  - Add PEOPLE_PICKER permission type with VIEW_USERS and VIEW_GROUPS permissions
  - Create custom middleware for query-aware permission validation
  - Implement permission-based type filtering in PeoplePicker component
  - Hide people picker UI when user lacks permissions, show only public toggle
  - Support granular access: users-only, groups-only, or mixed search modes

refactor: Replace marketplace interface config with permission-based system

  - Add MARKETPLACE permission type to handle marketplace access control
  - Update interface configuration to use role-based marketplace settings (admin/user)
  - Replace direct marketplace boolean config with permission-based checks
  - Modify frontend components to use marketplace permissions instead of interface config
  - Update agent query hooks to use marketplace permissions for determining permission levels
  - Add marketplace configuration structure similar to peoplePicker in YAML config
  - Backend now sets MARKETPLACE permissions based on interface configuration
  - When marketplace enabled: users get agents with EDIT permissions in dropdown lists  (builder mode)
  - When marketplace disabled: users get agents with VIEW permissions  in dropdown lists (browse mode)

🔧 fix: Redirect to New Chat if No Marketplace Access and Required Agent Name Placeholder (#8213)

* Fix: Fix the redirect to new chat page if access to marketplace is denied

* Fixed the required agent name placeholder

---------

Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com>

chore: fix tests, remove unnecessary imports

refactor: Implement permission checks for file access via agents

- Updated `hasAccessToFilesViaAgent` to utilize permission checks for VIEW and EDIT access.
- Replaced project-based access validation with permission-based checks.
- Enhanced tests to cover new permission logic and ensure proper access control for files associated with agents.
- Cleaned up imports and initialized models in test files for consistency.

refactor: Enhance test setup and cleanup for file access control

- Introduced modelsToCleanup array to track models added during tests for proper cleanup.
- Updated afterAll hooks in test files to ensure all collections are cleared and only added models are deleted.
- Improved consistency in model initialization across test files.
- Added comments for clarity on cleanup processes and test data management.

chore: Update Jest configuration and test setup for improved timeout handling

- Added a global test timeout of 30 seconds in jest.config.js.
- Configured jest.setTimeout in jestSetup.js to allow individual test overrides if needed.
- Enhanced test reliability by ensuring consistent timeout settings across all tests.

refactor: Implement file access filtering based on agent permissions

- Introduced `filterFilesByAgentAccess` function to filter files based on user access through agents.
- Updated `getFiles` and `primeFiles` functions to utilize the new filtering logic.
- Moved `hasAccessToFilesViaAgent` function from the File model to permission services, adjusting imports accordingly
- Enhanced tests to ensure proper access control and filtering behavior for files associated with agents.

fix: make support_contact field a nested object rather than a sub-document

refactor: Update support_contact field initialization in agent model

- Removed handling for empty support_contact object in createAgent function.
- Changed default value of support_contact in agent schema to undefined.

test: Add comprehensive tests for support_contact field handling and versioning

refactor: remove unused avatar upload mutation field and add informational toast for success

chore: add missing SidePanelProvider for AgentMarketplace and organize imports

fix: resolve agent selection race condition in marketplace HandleStartChat
- Set agent in localStorage before newConversation to prevent useSelectorEffects from auto-selecting previous agent

fix: resolve agent dropdown showing raw ID instead of agent info from URL

  - Add proactive agent fetching when agent_id is present in URL parameters
  - Inject fetched agent into agents cache so dropdowns display proper name/avatar
  - Use useAgentsMap dependency to ensure proper cache initialization timing
  - Prevents raw agent IDs from showing in UI when visiting shared agent links

Fix: Agents endpoint renamed to "My Agent" for less confusion with the Marketplace agents.

chore: fix ESLint issues and Test Mocks

ci: update permissions structure in loadDefaultInterface tests

- Refactored permissions for MEMORY and added new permissions for MARKETPLACE and PEOPLE_PICKER.
- Ensured consistent structure for permissions across different types.

feat:  support_contact validation to allow empty email strings
2025-08-13 16:24:18 -04:00

488 lines
14 KiB
TypeScript

import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { createAclEntryMethods } from './aclEntry';
import { PermissionBits } from '~/common';
import aclEntrySchema from '~/schema/aclEntry';
import type * as t from '~/types';
let mongoServer: MongoMemoryServer;
let AclEntry: mongoose.Model<t.IAclEntry>;
let methods: ReturnType<typeof createAclEntryMethods>;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
AclEntry = mongoose.models.AclEntry || mongoose.model('AclEntry', aclEntrySchema);
methods = createAclEntryMethods(mongoose);
await mongoose.connect(mongoUri);
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
beforeEach(async () => {
await mongoose.connection.dropDatabase();
});
describe('AclEntry Model Tests', () => {
/** Common test data */
const userId = new mongoose.Types.ObjectId();
const groupId = new mongoose.Types.ObjectId();
const resourceId = new mongoose.Types.ObjectId();
const grantedById = new mongoose.Types.ObjectId();
describe('Permission Grant and Query', () => {
test('should grant permission to a user', async () => {
const entry = await methods.grantPermission(
'user',
userId,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
expect(entry).toBeDefined();
expect(entry?.principalType).toBe('user');
expect(entry?.principalId?.toString()).toBe(userId.toString());
expect(entry?.principalModel).toBe('User');
expect(entry?.resourceType).toBe('agent');
expect(entry?.resourceId.toString()).toBe(resourceId.toString());
expect(entry?.permBits).toBe(PermissionBits.VIEW);
expect(entry?.grantedBy?.toString()).toBe(grantedById.toString());
expect(entry?.grantedAt).toBeInstanceOf(Date);
});
test('should grant permission to a group', async () => {
const entry = await methods.grantPermission(
'group',
groupId,
'agent',
resourceId,
PermissionBits.VIEW | PermissionBits.EDIT,
grantedById,
);
expect(entry).toBeDefined();
expect(entry?.principalType).toBe('group');
expect(entry?.principalId?.toString()).toBe(groupId.toString());
expect(entry?.principalModel).toBe('Group');
expect(entry?.permBits).toBe(PermissionBits.VIEW | PermissionBits.EDIT);
});
test('should grant public permission', async () => {
const entry = await methods.grantPermission(
'public',
null,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
expect(entry).toBeDefined();
expect(entry?.principalType).toBe('public');
expect(entry?.principalId).toBeUndefined();
expect(entry?.principalModel).toBeUndefined();
});
test('should find entries by principal', async () => {
/** Create two different permissions for the same user */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
await methods.grantPermission(
'user',
userId,
'project',
new mongoose.Types.ObjectId(),
PermissionBits.EDIT,
grantedById,
);
/** Find all entries for the user */
const entries = await methods.findEntriesByPrincipal('user', userId);
expect(entries).toHaveLength(2);
/** Find entries filtered by resource type */
const agentEntries = await methods.findEntriesByPrincipal('user', userId, 'agent');
expect(agentEntries).toHaveLength(1);
expect(agentEntries[0].resourceType).toBe('agent');
});
test('should find entries by resource', async () => {
/** Grant permissions to different principals for the same resource */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
await methods.grantPermission(
'group',
groupId,
'agent',
resourceId,
PermissionBits.EDIT,
grantedById,
);
await methods.grantPermission(
'public',
null,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
const entries = await methods.findEntriesByResource('agent', resourceId);
expect(entries).toHaveLength(3);
});
});
describe('Permission Checks', () => {
beforeEach(async () => {
/** Setup test data with various permissions */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
await methods.grantPermission(
'group',
groupId,
'agent',
resourceId,
PermissionBits.EDIT,
grantedById,
);
const otherResourceId = new mongoose.Types.ObjectId();
await methods.grantPermission(
'public',
null,
'agent',
otherResourceId,
PermissionBits.VIEW,
grantedById,
);
});
test('should find entries by principals and resource', async () => {
const principalsList = [
{ principalType: 'user', principalId: userId },
{ principalType: 'group', principalId: groupId },
];
const entries = await methods.findEntriesByPrincipalsAndResource(
principalsList,
'agent',
resourceId,
);
expect(entries).toHaveLength(2);
});
test('should check if user has permission', async () => {
const principalsList = [{ principalType: 'user', principalId: userId }];
/** User has VIEW permission */
const hasViewPermission = await methods.hasPermission(
principalsList,
'agent',
resourceId,
PermissionBits.VIEW,
);
expect(hasViewPermission).toBe(true);
/** User doesn't have EDIT permission */
const hasEditPermission = await methods.hasPermission(
principalsList,
'agent',
resourceId,
PermissionBits.EDIT,
);
expect(hasEditPermission).toBe(false);
});
test('should check if group has permission', async () => {
const principalsList = [{ principalType: 'group', principalId: groupId }];
/** Group has EDIT permission */
const hasEditPermission = await methods.hasPermission(
principalsList,
'agent',
resourceId,
PermissionBits.EDIT,
);
expect(hasEditPermission).toBe(true);
});
test('should check permission for multiple principals', async () => {
const principalsList = [
{ principalType: 'user', principalId: userId },
{ principalType: 'group', principalId: groupId },
];
/** User has VIEW and group has EDIT, together they should have both */
const hasViewPermission = await methods.hasPermission(
principalsList,
'agent',
resourceId,
PermissionBits.VIEW,
);
expect(hasViewPermission).toBe(true);
const hasEditPermission = await methods.hasPermission(
principalsList,
'agent',
resourceId,
PermissionBits.EDIT,
);
expect(hasEditPermission).toBe(true);
/** Neither has DELETE permission */
const hasDeletePermission = await methods.hasPermission(
principalsList,
'agent',
resourceId,
PermissionBits.DELETE,
);
expect(hasDeletePermission).toBe(false);
});
test('should get effective permissions', async () => {
const principalsList = [
{ principalType: 'user', principalId: userId },
{ principalType: 'group', principalId: groupId },
];
const effective = await methods.getEffectivePermissions(principalsList, 'agent', resourceId);
/** Combined permissions should be VIEW | EDIT */
expect(effective).toBe(PermissionBits.VIEW | PermissionBits.EDIT);
});
});
describe('Permission Modification', () => {
test('should revoke permission', async () => {
/** Grant permission first */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
/** Check it exists */
const entriesBefore = await methods.findEntriesByPrincipal('user', userId);
expect(entriesBefore).toHaveLength(1);
/** Revoke it */
const result = await methods.revokePermission('user', userId, 'agent', resourceId);
expect(result.deletedCount).toBe(1);
/** Verify it's gone */
const entriesAfter = await methods.findEntriesByPrincipal('user', userId);
expect(entriesAfter).toHaveLength(0);
});
test('should modify permission bits - add permissions', async () => {
/** Start with VIEW permission */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
/** Add EDIT permission */
const updated = await methods.modifyPermissionBits(
'user',
userId,
'agent',
resourceId,
PermissionBits.EDIT,
null,
);
expect(updated).toBeDefined();
expect(updated?.permBits).toBe(PermissionBits.VIEW | PermissionBits.EDIT);
});
test('should modify permission bits - remove permissions', async () => {
/** Start with VIEW | EDIT permissions */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId,
PermissionBits.VIEW | PermissionBits.EDIT,
grantedById,
);
/** Remove EDIT permission */
const updated = await methods.modifyPermissionBits(
'user',
userId,
'agent',
resourceId,
null,
PermissionBits.EDIT,
);
expect(updated).toBeDefined();
expect(updated?.permBits).toBe(PermissionBits.VIEW);
});
test('should modify permission bits - add and remove at once', async () => {
/** Start with VIEW permission */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId,
PermissionBits.VIEW,
grantedById,
);
/** Add EDIT and remove VIEW in one operation */
const updated = await methods.modifyPermissionBits(
'user',
userId,
'agent',
resourceId,
PermissionBits.EDIT,
PermissionBits.VIEW,
);
expect(updated).toBeDefined();
expect(updated?.permBits).toBe(PermissionBits.EDIT);
});
});
describe('Resource Access Queries', () => {
test('should find accessible resources', async () => {
/** Create multiple resources with different permissions */
const resourceId1 = new mongoose.Types.ObjectId();
const resourceId2 = new mongoose.Types.ObjectId();
const resourceId3 = new mongoose.Types.ObjectId();
/** User can view resource 1 */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId1,
PermissionBits.VIEW,
grantedById,
);
/** User can view and edit resource 2 */
await methods.grantPermission(
'user',
userId,
'agent',
resourceId2,
PermissionBits.VIEW | PermissionBits.EDIT,
grantedById,
);
/** Group can view resource 3 */
await methods.grantPermission(
'group',
groupId,
'agent',
resourceId3,
PermissionBits.VIEW,
grantedById,
);
/** Find resources with VIEW permission for user */
const userViewableResources = await methods.findAccessibleResources(
[{ principalType: 'user', principalId: userId }],
'agent',
PermissionBits.VIEW,
);
expect(userViewableResources).toHaveLength(2);
expect(userViewableResources.map((r) => r.toString()).sort()).toEqual(
[resourceId1.toString(), resourceId2.toString()].sort(),
);
/** Find resources with VIEW permission for user or group */
const allViewableResources = await methods.findAccessibleResources(
[
{ principalType: 'user', principalId: userId },
{ principalType: 'group', principalId: groupId },
],
'agent',
PermissionBits.VIEW,
);
expect(allViewableResources).toHaveLength(3);
/** Find resources with EDIT permission for user */
const editableResources = await methods.findAccessibleResources(
[{ principalType: 'user', principalId: userId }],
'agent',
PermissionBits.EDIT,
);
expect(editableResources).toHaveLength(1);
expect(editableResources[0].toString()).toBe(resourceId2.toString());
});
test('should handle inherited permissions', async () => {
const projectId = new mongoose.Types.ObjectId();
const childResourceId = new mongoose.Types.ObjectId();
/** Grant permission on project */
await methods.grantPermission(
'user',
userId,
'project',
projectId,
PermissionBits.VIEW,
grantedById,
);
/** Grant inherited permission on child resource */
await AclEntry.create({
principalType: 'user',
principalId: userId,
principalModel: 'User',
resourceType: 'agent',
resourceId: childResourceId,
permBits: PermissionBits.VIEW,
grantedBy: grantedById,
inheritedFrom: projectId,
});
/** Get effective permissions */
const effective = await methods.getEffectivePermissions(
[{ principalType: 'user', principalId: userId }],
'agent',
childResourceId,
);
/** Should have VIEW permission from inherited entry */
expect(effective).toBe(PermissionBits.VIEW);
});
});
});