LibreChat/api/server/routes/accessPermissions.js

123 lines
3.8 KiB
JavaScript
Raw Normal View History

const express = require('express');
🔧 refactor: Organize Sharing/Agent Components and Improve Type Safety refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids, rename enums to PascalCase refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids chore: move sharing related components to dedicated "Sharing" directory chore: remove PublicSharingToggle component and update index exports chore: move non-sidepanel agent components to `~/components/Agents` chore: move AgentCategoryDisplay component with tests chore: remove commented out code refactor: change PERMISSION_BITS from const to enum for better type safety refactor: reorganize imports in GenericGrantAccessDialog and update index exports for hooks refactor: update type definitions to use ACCESS_ROLE_IDS for improved type safety refactor: remove unused canAccessPromptResource middleware and related code refactor: remove unused prompt access roles from createAccessRoleMethods refactor: update resourceType in AclEntry type definition to remove unused 'prompt' value refactor: introduce ResourceType enum and update resourceType usage across data provider files for improved type safety refactor: update resourceType usage to ResourceType enum across sharing and permissions components for improved type safety refactor: standardize resourceType usage to ResourceType enum across agent and prompt models, permissions controller, and middleware for enhanced type safety refactor: update resourceType references from PROMPT_GROUP to PROMPTGROUP for consistency across models, middleware, and components refactor: standardize access role IDs and resource type usage across agent, file, and prompt models for improved type safety and consistency chore: add typedefs for TUpdateResourcePermissionsRequest and TUpdateResourcePermissionsResponse to enhance type definitions chore: move SearchPicker to PeoplePicker dir refactor: implement debouncing for query changes in SearchPicker for improved performance chore: fix typing, import order for agent admin settings fix: agent admin settings, prevent agent form submission refactor: rename `ACCESS_ROLE_IDS` to `AccessRoleIds` refactor: replace PermissionBits with PERMISSION_BITS refactor: replace PERMISSION_BITS with PermissionBits
2025-07-28 17:52:36 -04:00
const { ResourceType, PermissionBits } = require('librechat-data-provider');
const {
getUserEffectivePermissions,
🏗️ feat: Dynamic MCP Server Infrastructure with Access Control (#10787) * Feature: Dynamic MCP Server with Full UI Management * 🚦 feat: Add MCP Connection Status icons to MCPBuilder panel (#10805) * feature: Add MCP server connection status icons to MCPBuilder panel * refactor: Simplify MCPConfigDialog rendering in MCPBuilderPanel --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Danny Avila <danny@librechat.ai> * fix: address code review feedback for MCP server management - Fix OAuth secret preservation to avoid mutating input parameter by creating a merged config copy in ServerConfigsDB.update() - Improve error handling in getResourcePermissionsMap to propagate critical errors instead of silently returning empty Map - Extract duplicated MCP server filter logic by exposing selectableServers from useMCPServerManager hook and using it in MCPSelect component * test: Update PermissionService tests to throw errors on invalid resource types - Changed the test for handling invalid resource types to ensure it throws an error instead of returning an empty permissions map. - Updated the expectation to check for the specific error message when an invalid resource type is provided. * feat: Implement retry logic for MCP server creation to handle race conditions - Enhanced the createMCPServer method to include retry logic with exponential backoff for handling duplicate key errors during concurrent server creation. - Updated tests to verify that all concurrent requests succeed and that unique server names are generated. - Added a helper function to identify MongoDB duplicate key errors, improving error handling during server creation. * refactor: StatusIcon to use CircleCheck for connected status - Replaced the PlugZap icon with CircleCheck in the ConnectedStatusIcon component to better represent the connected state. - Ensured consistent icon usage across the component for improved visual clarity. * test: Update AccessControlService tests to throw errors on invalid resource types - Modified the test for invalid resource types to ensure it throws an error with a specific message instead of returning an empty permissions map. - This change enhances error handling and improves test coverage for the AccessControlService. * fix: Update error message for missing server name in MCP server retrieval - Changed the error message returned when the server name is not provided from 'MCP ID is required' to 'Server name is required' for better clarity and accuracy in the API response. --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Danny Avila <danny@librechat.ai>
2025-12-04 21:37:23 +01:00
getAllEffectivePermissions,
updateResourcePermissions,
getResourcePermissions,
getResourceRoles,
searchPrincipals,
} = require('~/server/controllers/PermissionsController');
const { requireJwtAuth, checkBan, uaParser, canAccessResource } = require('~/server/middleware');
🏪 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-06-11 22:55:07 +05:30
const { checkPeoplePickerAccess } = require('~/server/middleware/checkPeoplePickerAccess');
🔧 refactor: Permission handling for Resource Sharing (#11283) * 🔧 refactor: permission handling for public sharing - Updated permission keys from SHARED_GLOBAL to SHARE across various files for consistency. - Added public access configuration in librechat.example.yaml. - Adjusted related tests and components to reflect the new permission structure. * chore: Update default SHARE permission to false * fix: Update SHARE permissions in tests and implementation - Added SHARE permission handling for user and admin roles in permissions.spec.ts and permissions.ts. - Updated expected permissions in tests to reflect new SHARE permission values for various permission types. * fix: Handle undefined values in PeoplePickerAdminSettings component - Updated the checked and value props of the Switch component to handle undefined values gracefully by defaulting to false. This ensures consistent behavior when the field value is not set. * feat: Add CREATE permission handling for prompts and agents - Introduced CREATE permission for user and admin roles in permissions.spec.ts and permissions.ts. - Updated expected permissions in tests to include CREATE permission for various permission types. * 🔧 refactor: Enhance permission handling for sharing dialog usability * refactor: public sharing permissions for resources - Added middleware to check SHARE_PUBLIC permissions for agents, prompts, and MCP servers. - Updated interface configuration in librechat.example.yaml to include public sharing options. - Enhanced components and hooks to support public sharing functionality. - Adjusted tests to validate new permission handling for public sharing across various resource types. * refactor: update Share2Icon styling in GenericGrantAccessDialog * refactor: update Share2Icon size in GenericGrantAccessDialog for consistency * refactor: improve layout and styling of Share2Icon in GenericGrantAccessDialog * refactor: update Share2Icon size in GenericGrantAccessDialog for improved consistency * chore: remove redundant public sharing option from People Picker * refactor: add SHARE_PUBLIC permission handling in updateInterfacePermissions tests
2026-01-10 14:02:56 -05:00
const { checkSharePublicAccess } = require('~/server/middleware/checkSharePublicAccess');
const { findMCPServerByObjectId } = require('~/models');
const router = express.Router();
// Apply common middleware
router.use(requireJwtAuth);
router.use(checkBan);
router.use(uaParser);
/**
* Generic routes for resource permissions
* Pattern: /api/permissions/{resourceType}/{resourceId}
*/
/**
* GET /api/permissions/search-principals
* Search for users and groups to grant permissions
*/
🏪 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-06-11 22:55:07 +05:30
router.get('/search-principals', checkPeoplePickerAccess, searchPrincipals);
/**
* GET /api/permissions/{resourceType}/roles
* Get available roles for a resource type
*/
router.get('/:resourceType/roles', getResourceRoles);
🔒 fix: Access Control on Agent Permission Queries (#11145) Adds access control check to GET /api/permissions/:resourceType/:resourceId endpoint to prevent unauthorized disclosure of agent permission information. ## Vulnerability Summary LibreChat version 0.8.1-rc2 did not enforce proper access control when querying agent permissions. Any authenticated user could read the permissions of arbitrary agents by knowing the agent ID, even for private agents they had no access to. **Impact:** - Attackers could enumerate which users have access to private agents - Permission levels (owner, editor, viewer) were exposed - User emails and names of permitted users were disclosed - Agent's public/private sharing status was revealed **Attack Vector:** ``` GET /api/permissions/agent/{agent_id} Authorization: Bearer <any_valid_token> ``` The MongoDB ObjectId format (timestamp + process ID + counter) made it feasible to brute-force discover valid agent IDs. ## Fix Added `checkResourcePermissionAccess` middleware factory that enforces SHARE permission before allowing access to permission queries. This middleware is now applied to the GET endpoint, matching the existing access control on the PUT endpoint. **Before:** ```javascript router.get('/:resourceType/:resourceId', getResourcePermissions); ``` **After:** ```javascript router.get( '/:resourceType/:resourceId', checkResourcePermissionAccess(PermissionBits.SHARE), getResourcePermissions, ); ``` The middleware handles all supported resource types: - Agent (ResourceType.AGENT) - Prompt Group (ResourceType.PROMPTGROUP) - MCP Server (ResourceType.MCPSERVER) ## Code Changes **api/server/routes/accessPermissions.js:** - Added `checkResourcePermissionAccess()` middleware factory - Applied middleware to GET /:resourceType/:resourceId endpoint - Refactored PUT endpoint to use the same middleware factory (DRY) **api/server/routes/accessPermissions.test.js:** - Added security tests verifying unauthorized access is denied - Tests confirm 403 Forbidden for users without SHARE permission ## Security Tests ``` ✓ should deny permission query for user without access (main vulnerability test) ✓ should return 400 for unsupported resource type ✓ should deny permission update for user without access
2025-12-29 15:10:31 -05:00
/**
* Middleware factory to check resource access for permission-related operations.
* SECURITY: Users must have SHARE permission to view or modify resource permissions.
* @param {string} requiredPermission - The permission bit required (e.g., SHARE)
* @returns Express middleware function
*/
const checkResourcePermissionAccess = (requiredPermission) => (req, res, next) => {
const { resourceType } = req.params;
let middleware;
if (resourceType === ResourceType.AGENT) {
middleware = canAccessResource({
resourceType: ResourceType.AGENT,
requiredPermission,
resourceIdParam: 'resourceId',
});
🛸 feat: Remote Agent Access with External API Support (#11503) * 🪪 feat: Microsoft Graph Access Token Placeholder for MCP Servers (#10867) * feat: MCP Graph Token env var * Addressing copilot remarks * Addressed Copilot review remarks * Fixed graphtokenservice mock in MCP test suite * fix: remove unnecessary type check and cast in resolveGraphTokensInRecord * ci: add Graph Token integration tests in MCPManager * refactor: update user type definitions to use Partial<IUser> in multiple functions * test: enhance MCP tests for graph token processing and user placeholder resolution - Added comprehensive tests to validate the interaction between preProcessGraphTokens and processMCPEnv. - Ensured correct resolution of graph tokens and user placeholders in various configurations. - Mocked OIDC utilities to facilitate testing of token extraction and validation. - Verified that original options remain unchanged after processing. * chore: import order * chore: imports --------- Co-authored-by: Danny Avila <danny@librechat.ai> * WIP: OpenAI-compatible API for LibreChat agents - Added OpenAIChatCompletionController for handling chat completions. - Introduced ListModelsController and GetModelController for listing and retrieving agent details. - Created routes for OpenAI API endpoints, including /v1/chat/completions and /v1/models. - Developed event handlers for streaming responses in OpenAI format. - Implemented request validation and error handling for API interactions. - Integrated content aggregation and response formatting to align with OpenAI specifications. This commit establishes a foundational API for interacting with LibreChat agents in a manner compatible with OpenAI's chat completion interface. * refactor: OpenAI-spec content aggregation for improved performance and clarity * fix: OpenAI chat completion controller with safe user handling for correct tool loading * refactor: Remove conversation ID from OpenAI response context and related handlers * refactor: OpenAI chat completion handling with streaming support - Introduced a lightweight tracker for streaming responses, allowing for efficient tracking of emitted content and usage metadata. - Updated the OpenAIChatCompletionController to utilize the new tracker, improving the handling of streaming and non-streaming responses. - Refactored event handlers to accommodate the new streaming logic, ensuring proper management of tool calls and content aggregation. - Adjusted response handling to streamline error reporting during streaming sessions. * WIP: Open Responses API with core service, types, and handlers - Added Open Responses API module with comprehensive types and enums. - Implemented core service for processing requests, including validation and input conversion. - Developed event handlers for streaming responses and non-streaming aggregation. - Established response building logic and error handling mechanisms. - Created detailed types for input and output content, ensuring compliance with Open Responses specification. * feat: Implement response storage and retrieval in Open Responses API - Added functionality to save user input messages and assistant responses to the database when the `store` flag is set to true. - Introduced a new endpoint to retrieve stored responses by ID, allowing users to access previous interactions. - Enhanced the response creation process to include database operations for conversation and message storage. - Implemented tests to validate the storage and retrieval of responses, ensuring correct behavior for both existing and non-existent response IDs. * refactor: Open Responses API with additional token tracking and validation - Added support for tracking cached tokens in response usage, improving token management. - Updated response structure to include new properties for top log probabilities and detailed usage metrics. - Enhanced tests to validate the presence and types of new properties in API responses, ensuring compliance with updated specifications. - Refactored response handling to accommodate new fields and improve overall clarity and performance. * refactor: Update reasoning event handlers and types for consistency - Renamed reasoning text events to simplify naming conventions, changing `emitReasoningTextDelta` to `emitReasoningDelta` and `emitReasoningTextDone` to `emitReasoningDone`. - Updated event types in the API to reflect the new naming, ensuring consistency across the codebase. - Added `logprobs` property to output events for enhanced tracking of log probabilities. * feat: Add validation for streaming events in Open Responses API tests * feat: Implement response.created event in Open Responses API - Added emitResponseCreated function to emit the response.created event as the first event in the streaming sequence, adhering to the Open Responses specification. - Updated createResponse function to emit response.created followed by response.in_progress. - Enhanced tests to validate the order of emitted events, ensuring response.created is triggered before response.in_progress. * feat: Responses API with attachment event handling - Introduced `createResponsesToolEndCallback` to handle attachment events in the Responses API, emitting `librechat:attachment` events as per the Open Responses extension specification. - Updated the `createResponse` function to utilize the new callback for processing tool outputs and emitting attachments during streaming. - Added helper functions for writing attachment events and defined types for attachment data, ensuring compatibility with the Open Responses protocol. - Enhanced tests to validate the integration of attachment events within the Responses API workflow. * WIP: remote agent auth * fix: Improve loading state handling in AgentApiKeys component - Updated the rendering logic to conditionally display loading spinner and API keys based on the loading state. - Removed unnecessary imports and streamlined the component for better readability. * refactor: Update API key access handling in routes - Replaced `checkAccess` with `generateCheckAccess` for improved access control. - Consolidated access checks into a single `checkApiKeyAccess` function, enhancing code readability and maintainability. - Streamlined route definitions for creating, listing, retrieving, and deleting API keys. * fix: Add permission handling for REMOTE_AGENT resource type * feat: Enhance permission handling for REMOTE_AGENT resources - Updated the deleteAgent and deleteUserAgents functions to handle permissions for both AGENT and REMOTE_AGENT resource types. - Introduced new functions to enrich REMOTE_AGENT principals and backfill permissions for AGENT owners. - Modified createAgentHandler and duplicateAgentHandler to grant permissions for REMOTE_AGENT alongside AGENT. - Added utility functions for retrieving effective permissions for REMOTE_AGENT resources, ensuring consistent access control across the application. * refactor: Rename and update roles for remote agent access - Changed role name from API User to Editor in translation files for clarity. - Updated default editor role ID from REMOTE_AGENT_USER to REMOTE_AGENT_EDITOR in resource configurations. - Adjusted role localization to reflect the new Editor role. - Modified access permissions to align with the updated role definitions across the application. * feat: Introduce remote agent permissions and update access handling - Added support for REMOTE_AGENTS in permission schemas, including use, create, share, and share_public permissions. - Updated the interface configuration to include remote agent settings. - Modified middleware and API key access checks to align with the new remote agent permission structure. - Enhanced role defaults to incorporate remote agent permissions, ensuring consistent access control across the application. * refactor: Update AgentApiKeys component and permissions handling - Refactored the AgentApiKeys component to improve structure and readability, including the introduction of ApiKeysContent for better separation of concerns. - Updated CreateKeyDialog to accept an onKeyCreated callback, enhancing its functionality. - Adjusted permission checks in Data component to use REMOTE_AGENTS and USE permissions, aligning with recent permission schema changes. - Enhanced loading state handling and dialog management for a smoother user experience. * refactor: Update remote agent access checks in API routes - Replaced existing access checks with `generateCheckAccess` for remote agents in the API keys and agents routes. - Introduced specific permission checks for creating, listing, retrieving, and deleting API keys, enhancing access control. - Improved code structure by consolidating permission handling for remote agents across multiple routes. * fix: Correct query parameters in ApiKeysContent component - Updated the useGetAgentApiKeysQuery call to include an object for the enabled parameter, ensuring proper functionality when the component is open. - This change improves the handling of API key retrieval based on the component's open state. * feat: Implement remote agents permissions and update API routes - Added new API route for updating remote agents permissions, enhancing role management capabilities. - Introduced remote agents permissions handling in the AgentApiKeys component, including a dedicated settings dialog. - Updated localization files to include new remote agents permission labels for better user experience. - Refactored data provider to support remote agents permissions updates, ensuring consistent access control across the application. * feat: Add remote agents permissions to role schema and interface - Introduced new permissions for REMOTE_AGENTS in the role schema, including USE, CREATE, SHARE, and SHARE_PUBLIC. - Updated the IRole interface to reflect the new remote agents permissions structure, enhancing role management capabilities. * feat: Add remote agents settings button to API keys dialog * feat: Update AgentFooter to include remote agent sharing permissions - Refactored access checks to incorporate permissions for sharing remote agents. - Enhanced conditional rendering logic to allow sharing by users with remote agent permissions. - Improved loading state handling for remote agent permissions, ensuring a smoother user experience. * refactor: Update API key creation access check and localization strings - Replaced the access check for creating API keys to use the existing remote agents access check. - Updated localization strings to correct the descriptions for remote agent permissions, ensuring clarity in user interface. * fix: resource permission mapping to include remote agents - Changed the resourceToPermissionMap to use a Partial<Record> for better flexibility. - Added mapping for REMOTE_AGENT permissions, enhancing the sharing capabilities for remote agents. * feat: Implement remote access checks for agent models - Enhanced ListModelsController and GetModelController to include checks for user permissions on remote agents. - Integrated findAccessibleResources to filter agents based on VIEW permission for REMOTE_AGENT. - Updated response handling to ensure users can only access agents they have permissions for, improving security and access control. * fix: Update user parameter type in processUserPlaceholders function - Changed the user parameter type in the processUserPlaceholders function from Partial<Partial<IUser>> to Partial<IUser> for improved type clarity and consistency. * refactor: Simplify integration test structure by removing conditional describe - Replaced conditional describeWithApiKey with a standard describe for all integration tests in responses.spec.js. - This change enhances test clarity and ensures all tests are executed consistently, regardless of the SKIP_INTEGRATION_TESTS flag. * test: Update AgentFooter tests to reflect new grant access dialog ID - Changed test IDs for the grant access dialog in AgentFooter tests to include the resource type, ensuring accurate identification in the test cases. - This update improves test clarity and aligns with recent changes in the component's implementation. * test: Enhance integration tests for Open Responses API - Updated integration tests in responses.spec.js to utilize an authRequest helper for consistent authorization handling across all test cases. - Introduced a test user and API key creation to improve test setup and ensure proper permission checks for remote agents. - Added checks for existing access roles and created necessary roles if they do not exist, enhancing test reliability and coverage. * feat: Extend accessRole schema to include remoteAgent resource type - Updated the accessRole schema to add 'remoteAgent' to the resourceType enum, enhancing the flexibility of role assignments and permissions management. * test: refactored test setup to create a minimal Express app for responses routes, enhancing test structure and maintainability. * test: Enhance abort.spec.js by mocking additional modules for improved test isolation - Updated the test setup in abort.spec.js to include actual implementations of '@librechat/data-schemas' and '@librechat/api' while maintaining mock functionality. - This change improves test reliability and ensures that the tests are more representative of the actual module behavior. * refactor: Update conversation ID generation to use UUID - Replaced the nanoid with uuidv4 for generating conversation IDs in the createResponse function, enhancing uniqueness and consistency in ID generation. * test: Add remote agent access roles to AccessRole model tests - Included additional access roles for remote agents (REMOTE_AGENT_EDITOR, REMOTE_AGENT_OWNER, REMOTE_AGENT_VIEWER) in the AccessRole model tests to ensure comprehensive coverage of role assignments and permissions management. * chore: Add deletion of user agent API keys in user deletion process - Updated the user deletion process in UserController and delete-user.js to include the removal of user agent API keys, ensuring comprehensive cleanup of user data upon account deletion. * test: Add remote agents permissions to permissions.spec.ts - Enhanced the permissions tests by including comprehensive permission settings for remote agents across various scenarios, ensuring accurate validation of access controls for remote agent roles. * chore: Update remote agents translations for clarity and consistency - Removed outdated remote agents translation entries and added revised entries to improve clarity on API key creation and sharing permissions for remote agents. This enhances user understanding of the available functionalities. * feat: Add indexing and TTL for agent API keys - Introduced an index on the `key` field for improved query performance. - Added a TTL index on the `expiresAt` field to enable automatic cleanup of expired API keys, ensuring efficient management of stored keys. * chore: Update API route documentation for clarity - Revised comments in the agents route file to clarify the handling of API key authentication. - Removed outdated endpoint listings to streamline the documentation and focus on current functionality. --------- Co-authored-by: Max Sanna <max@maxsanna.com>
2026-01-26 10:50:30 -05:00
} else if (resourceType === ResourceType.REMOTE_AGENT) {
middleware = canAccessResource({
resourceType: ResourceType.REMOTE_AGENT,
requiredPermission,
resourceIdParam: 'resourceId',
});
🔒 fix: Access Control on Agent Permission Queries (#11145) Adds access control check to GET /api/permissions/:resourceType/:resourceId endpoint to prevent unauthorized disclosure of agent permission information. ## Vulnerability Summary LibreChat version 0.8.1-rc2 did not enforce proper access control when querying agent permissions. Any authenticated user could read the permissions of arbitrary agents by knowing the agent ID, even for private agents they had no access to. **Impact:** - Attackers could enumerate which users have access to private agents - Permission levels (owner, editor, viewer) were exposed - User emails and names of permitted users were disclosed - Agent's public/private sharing status was revealed **Attack Vector:** ``` GET /api/permissions/agent/{agent_id} Authorization: Bearer <any_valid_token> ``` The MongoDB ObjectId format (timestamp + process ID + counter) made it feasible to brute-force discover valid agent IDs. ## Fix Added `checkResourcePermissionAccess` middleware factory that enforces SHARE permission before allowing access to permission queries. This middleware is now applied to the GET endpoint, matching the existing access control on the PUT endpoint. **Before:** ```javascript router.get('/:resourceType/:resourceId', getResourcePermissions); ``` **After:** ```javascript router.get( '/:resourceType/:resourceId', checkResourcePermissionAccess(PermissionBits.SHARE), getResourcePermissions, ); ``` The middleware handles all supported resource types: - Agent (ResourceType.AGENT) - Prompt Group (ResourceType.PROMPTGROUP) - MCP Server (ResourceType.MCPSERVER) ## Code Changes **api/server/routes/accessPermissions.js:** - Added `checkResourcePermissionAccess()` middleware factory - Applied middleware to GET /:resourceType/:resourceId endpoint - Refactored PUT endpoint to use the same middleware factory (DRY) **api/server/routes/accessPermissions.test.js:** - Added security tests verifying unauthorized access is denied - Tests confirm 403 Forbidden for users without SHARE permission ## Security Tests ``` ✓ should deny permission query for user without access (main vulnerability test) ✓ should return 400 for unsupported resource type ✓ should deny permission update for user without access
2025-12-29 15:10:31 -05:00
} else if (resourceType === ResourceType.PROMPTGROUP) {
middleware = canAccessResource({
resourceType: ResourceType.PROMPTGROUP,
requiredPermission,
resourceIdParam: 'resourceId',
});
} else if (resourceType === ResourceType.MCPSERVER) {
middleware = canAccessResource({
resourceType: ResourceType.MCPSERVER,
requiredPermission,
resourceIdParam: 'resourceId',
idResolver: findMCPServerByObjectId,
🔒 fix: Access Control on Agent Permission Queries (#11145) Adds access control check to GET /api/permissions/:resourceType/:resourceId endpoint to prevent unauthorized disclosure of agent permission information. ## Vulnerability Summary LibreChat version 0.8.1-rc2 did not enforce proper access control when querying agent permissions. Any authenticated user could read the permissions of arbitrary agents by knowing the agent ID, even for private agents they had no access to. **Impact:** - Attackers could enumerate which users have access to private agents - Permission levels (owner, editor, viewer) were exposed - User emails and names of permitted users were disclosed - Agent's public/private sharing status was revealed **Attack Vector:** ``` GET /api/permissions/agent/{agent_id} Authorization: Bearer <any_valid_token> ``` The MongoDB ObjectId format (timestamp + process ID + counter) made it feasible to brute-force discover valid agent IDs. ## Fix Added `checkResourcePermissionAccess` middleware factory that enforces SHARE permission before allowing access to permission queries. This middleware is now applied to the GET endpoint, matching the existing access control on the PUT endpoint. **Before:** ```javascript router.get('/:resourceType/:resourceId', getResourcePermissions); ``` **After:** ```javascript router.get( '/:resourceType/:resourceId', checkResourcePermissionAccess(PermissionBits.SHARE), getResourcePermissions, ); ``` The middleware handles all supported resource types: - Agent (ResourceType.AGENT) - Prompt Group (ResourceType.PROMPTGROUP) - MCP Server (ResourceType.MCPSERVER) ## Code Changes **api/server/routes/accessPermissions.js:** - Added `checkResourcePermissionAccess()` middleware factory - Applied middleware to GET /:resourceType/:resourceId endpoint - Refactored PUT endpoint to use the same middleware factory (DRY) **api/server/routes/accessPermissions.test.js:** - Added security tests verifying unauthorized access is denied - Tests confirm 403 Forbidden for users without SHARE permission ## Security Tests ``` ✓ should deny permission query for user without access (main vulnerability test) ✓ should return 400 for unsupported resource type ✓ should deny permission update for user without access
2025-12-29 15:10:31 -05:00
});
} else {
return res.status(400).json({
error: 'Bad Request',
message: `Unsupported resource type: ${resourceType}`,
});
}
// Execute the middleware
middleware(req, res, next);
};
/**
* GET /api/permissions/{resourceType}/{resourceId}
* Get all permissions for a specific resource
🔒 fix: Access Control on Agent Permission Queries (#11145) Adds access control check to GET /api/permissions/:resourceType/:resourceId endpoint to prevent unauthorized disclosure of agent permission information. ## Vulnerability Summary LibreChat version 0.8.1-rc2 did not enforce proper access control when querying agent permissions. Any authenticated user could read the permissions of arbitrary agents by knowing the agent ID, even for private agents they had no access to. **Impact:** - Attackers could enumerate which users have access to private agents - Permission levels (owner, editor, viewer) were exposed - User emails and names of permitted users were disclosed - Agent's public/private sharing status was revealed **Attack Vector:** ``` GET /api/permissions/agent/{agent_id} Authorization: Bearer <any_valid_token> ``` The MongoDB ObjectId format (timestamp + process ID + counter) made it feasible to brute-force discover valid agent IDs. ## Fix Added `checkResourcePermissionAccess` middleware factory that enforces SHARE permission before allowing access to permission queries. This middleware is now applied to the GET endpoint, matching the existing access control on the PUT endpoint. **Before:** ```javascript router.get('/:resourceType/:resourceId', getResourcePermissions); ``` **After:** ```javascript router.get( '/:resourceType/:resourceId', checkResourcePermissionAccess(PermissionBits.SHARE), getResourcePermissions, ); ``` The middleware handles all supported resource types: - Agent (ResourceType.AGENT) - Prompt Group (ResourceType.PROMPTGROUP) - MCP Server (ResourceType.MCPSERVER) ## Code Changes **api/server/routes/accessPermissions.js:** - Added `checkResourcePermissionAccess()` middleware factory - Applied middleware to GET /:resourceType/:resourceId endpoint - Refactored PUT endpoint to use the same middleware factory (DRY) **api/server/routes/accessPermissions.test.js:** - Added security tests verifying unauthorized access is denied - Tests confirm 403 Forbidden for users without SHARE permission ## Security Tests ``` ✓ should deny permission query for user without access (main vulnerability test) ✓ should return 400 for unsupported resource type ✓ should deny permission update for user without access
2025-12-29 15:10:31 -05:00
* SECURITY: Requires SHARE permission to view resource permissions
*/
🔒 fix: Access Control on Agent Permission Queries (#11145) Adds access control check to GET /api/permissions/:resourceType/:resourceId endpoint to prevent unauthorized disclosure of agent permission information. ## Vulnerability Summary LibreChat version 0.8.1-rc2 did not enforce proper access control when querying agent permissions. Any authenticated user could read the permissions of arbitrary agents by knowing the agent ID, even for private agents they had no access to. **Impact:** - Attackers could enumerate which users have access to private agents - Permission levels (owner, editor, viewer) were exposed - User emails and names of permitted users were disclosed - Agent's public/private sharing status was revealed **Attack Vector:** ``` GET /api/permissions/agent/{agent_id} Authorization: Bearer <any_valid_token> ``` The MongoDB ObjectId format (timestamp + process ID + counter) made it feasible to brute-force discover valid agent IDs. ## Fix Added `checkResourcePermissionAccess` middleware factory that enforces SHARE permission before allowing access to permission queries. This middleware is now applied to the GET endpoint, matching the existing access control on the PUT endpoint. **Before:** ```javascript router.get('/:resourceType/:resourceId', getResourcePermissions); ``` **After:** ```javascript router.get( '/:resourceType/:resourceId', checkResourcePermissionAccess(PermissionBits.SHARE), getResourcePermissions, ); ``` The middleware handles all supported resource types: - Agent (ResourceType.AGENT) - Prompt Group (ResourceType.PROMPTGROUP) - MCP Server (ResourceType.MCPSERVER) ## Code Changes **api/server/routes/accessPermissions.js:** - Added `checkResourcePermissionAccess()` middleware factory - Applied middleware to GET /:resourceType/:resourceId endpoint - Refactored PUT endpoint to use the same middleware factory (DRY) **api/server/routes/accessPermissions.test.js:** - Added security tests verifying unauthorized access is denied - Tests confirm 403 Forbidden for users without SHARE permission ## Security Tests ``` ✓ should deny permission query for user without access (main vulnerability test) ✓ should return 400 for unsupported resource type ✓ should deny permission update for user without access
2025-12-29 15:10:31 -05:00
router.get(
'/:resourceType/:resourceId',
checkResourcePermissionAccess(PermissionBits.SHARE),
getResourcePermissions,
);
/**
* PUT /api/permissions/{resourceType}/{resourceId}
* Bulk update permissions for a specific resource
🔒 fix: Access Control on Agent Permission Queries (#11145) Adds access control check to GET /api/permissions/:resourceType/:resourceId endpoint to prevent unauthorized disclosure of agent permission information. ## Vulnerability Summary LibreChat version 0.8.1-rc2 did not enforce proper access control when querying agent permissions. Any authenticated user could read the permissions of arbitrary agents by knowing the agent ID, even for private agents they had no access to. **Impact:** - Attackers could enumerate which users have access to private agents - Permission levels (owner, editor, viewer) were exposed - User emails and names of permitted users were disclosed - Agent's public/private sharing status was revealed **Attack Vector:** ``` GET /api/permissions/agent/{agent_id} Authorization: Bearer <any_valid_token> ``` The MongoDB ObjectId format (timestamp + process ID + counter) made it feasible to brute-force discover valid agent IDs. ## Fix Added `checkResourcePermissionAccess` middleware factory that enforces SHARE permission before allowing access to permission queries. This middleware is now applied to the GET endpoint, matching the existing access control on the PUT endpoint. **Before:** ```javascript router.get('/:resourceType/:resourceId', getResourcePermissions); ``` **After:** ```javascript router.get( '/:resourceType/:resourceId', checkResourcePermissionAccess(PermissionBits.SHARE), getResourcePermissions, ); ``` The middleware handles all supported resource types: - Agent (ResourceType.AGENT) - Prompt Group (ResourceType.PROMPTGROUP) - MCP Server (ResourceType.MCPSERVER) ## Code Changes **api/server/routes/accessPermissions.js:** - Added `checkResourcePermissionAccess()` middleware factory - Applied middleware to GET /:resourceType/:resourceId endpoint - Refactored PUT endpoint to use the same middleware factory (DRY) **api/server/routes/accessPermissions.test.js:** - Added security tests verifying unauthorized access is denied - Tests confirm 403 Forbidden for users without SHARE permission ## Security Tests ``` ✓ should deny permission query for user without access (main vulnerability test) ✓ should return 400 for unsupported resource type ✓ should deny permission update for user without access
2025-12-29 15:10:31 -05:00
* SECURITY: Requires SHARE permission to modify resource permissions
🔧 refactor: Permission handling for Resource Sharing (#11283) * 🔧 refactor: permission handling for public sharing - Updated permission keys from SHARED_GLOBAL to SHARE across various files for consistency. - Added public access configuration in librechat.example.yaml. - Adjusted related tests and components to reflect the new permission structure. * chore: Update default SHARE permission to false * fix: Update SHARE permissions in tests and implementation - Added SHARE permission handling for user and admin roles in permissions.spec.ts and permissions.ts. - Updated expected permissions in tests to reflect new SHARE permission values for various permission types. * fix: Handle undefined values in PeoplePickerAdminSettings component - Updated the checked and value props of the Switch component to handle undefined values gracefully by defaulting to false. This ensures consistent behavior when the field value is not set. * feat: Add CREATE permission handling for prompts and agents - Introduced CREATE permission for user and admin roles in permissions.spec.ts and permissions.ts. - Updated expected permissions in tests to include CREATE permission for various permission types. * 🔧 refactor: Enhance permission handling for sharing dialog usability * refactor: public sharing permissions for resources - Added middleware to check SHARE_PUBLIC permissions for agents, prompts, and MCP servers. - Updated interface configuration in librechat.example.yaml to include public sharing options. - Enhanced components and hooks to support public sharing functionality. - Adjusted tests to validate new permission handling for public sharing across various resource types. * refactor: update Share2Icon styling in GenericGrantAccessDialog * refactor: update Share2Icon size in GenericGrantAccessDialog for consistency * refactor: improve layout and styling of Share2Icon in GenericGrantAccessDialog * refactor: update Share2Icon size in GenericGrantAccessDialog for improved consistency * chore: remove redundant public sharing option from People Picker * refactor: add SHARE_PUBLIC permission handling in updateInterfacePermissions tests
2026-01-10 14:02:56 -05:00
* SECURITY: Requires SHARE_PUBLIC permission to enable public sharing
*/
router.put(
'/:resourceType/:resourceId',
🔒 fix: Access Control on Agent Permission Queries (#11145) Adds access control check to GET /api/permissions/:resourceType/:resourceId endpoint to prevent unauthorized disclosure of agent permission information. ## Vulnerability Summary LibreChat version 0.8.1-rc2 did not enforce proper access control when querying agent permissions. Any authenticated user could read the permissions of arbitrary agents by knowing the agent ID, even for private agents they had no access to. **Impact:** - Attackers could enumerate which users have access to private agents - Permission levels (owner, editor, viewer) were exposed - User emails and names of permitted users were disclosed - Agent's public/private sharing status was revealed **Attack Vector:** ``` GET /api/permissions/agent/{agent_id} Authorization: Bearer <any_valid_token> ``` The MongoDB ObjectId format (timestamp + process ID + counter) made it feasible to brute-force discover valid agent IDs. ## Fix Added `checkResourcePermissionAccess` middleware factory that enforces SHARE permission before allowing access to permission queries. This middleware is now applied to the GET endpoint, matching the existing access control on the PUT endpoint. **Before:** ```javascript router.get('/:resourceType/:resourceId', getResourcePermissions); ``` **After:** ```javascript router.get( '/:resourceType/:resourceId', checkResourcePermissionAccess(PermissionBits.SHARE), getResourcePermissions, ); ``` The middleware handles all supported resource types: - Agent (ResourceType.AGENT) - Prompt Group (ResourceType.PROMPTGROUP) - MCP Server (ResourceType.MCPSERVER) ## Code Changes **api/server/routes/accessPermissions.js:** - Added `checkResourcePermissionAccess()` middleware factory - Applied middleware to GET /:resourceType/:resourceId endpoint - Refactored PUT endpoint to use the same middleware factory (DRY) **api/server/routes/accessPermissions.test.js:** - Added security tests verifying unauthorized access is denied - Tests confirm 403 Forbidden for users without SHARE permission ## Security Tests ``` ✓ should deny permission query for user without access (main vulnerability test) ✓ should return 400 for unsupported resource type ✓ should deny permission update for user without access
2025-12-29 15:10:31 -05:00
checkResourcePermissionAccess(PermissionBits.SHARE),
🔧 refactor: Permission handling for Resource Sharing (#11283) * 🔧 refactor: permission handling for public sharing - Updated permission keys from SHARED_GLOBAL to SHARE across various files for consistency. - Added public access configuration in librechat.example.yaml. - Adjusted related tests and components to reflect the new permission structure. * chore: Update default SHARE permission to false * fix: Update SHARE permissions in tests and implementation - Added SHARE permission handling for user and admin roles in permissions.spec.ts and permissions.ts. - Updated expected permissions in tests to reflect new SHARE permission values for various permission types. * fix: Handle undefined values in PeoplePickerAdminSettings component - Updated the checked and value props of the Switch component to handle undefined values gracefully by defaulting to false. This ensures consistent behavior when the field value is not set. * feat: Add CREATE permission handling for prompts and agents - Introduced CREATE permission for user and admin roles in permissions.spec.ts and permissions.ts. - Updated expected permissions in tests to include CREATE permission for various permission types. * 🔧 refactor: Enhance permission handling for sharing dialog usability * refactor: public sharing permissions for resources - Added middleware to check SHARE_PUBLIC permissions for agents, prompts, and MCP servers. - Updated interface configuration in librechat.example.yaml to include public sharing options. - Enhanced components and hooks to support public sharing functionality. - Adjusted tests to validate new permission handling for public sharing across various resource types. * refactor: update Share2Icon styling in GenericGrantAccessDialog * refactor: update Share2Icon size in GenericGrantAccessDialog for consistency * refactor: improve layout and styling of Share2Icon in GenericGrantAccessDialog * refactor: update Share2Icon size in GenericGrantAccessDialog for improved consistency * chore: remove redundant public sharing option from People Picker * refactor: add SHARE_PUBLIC permission handling in updateInterfacePermissions tests
2026-01-10 14:02:56 -05:00
checkSharePublicAccess,
updateResourcePermissions,
);
🏗️ feat: Dynamic MCP Server Infrastructure with Access Control (#10787) * Feature: Dynamic MCP Server with Full UI Management * 🚦 feat: Add MCP Connection Status icons to MCPBuilder panel (#10805) * feature: Add MCP server connection status icons to MCPBuilder panel * refactor: Simplify MCPConfigDialog rendering in MCPBuilderPanel --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Danny Avila <danny@librechat.ai> * fix: address code review feedback for MCP server management - Fix OAuth secret preservation to avoid mutating input parameter by creating a merged config copy in ServerConfigsDB.update() - Improve error handling in getResourcePermissionsMap to propagate critical errors instead of silently returning empty Map - Extract duplicated MCP server filter logic by exposing selectableServers from useMCPServerManager hook and using it in MCPSelect component * test: Update PermissionService tests to throw errors on invalid resource types - Changed the test for handling invalid resource types to ensure it throws an error instead of returning an empty permissions map. - Updated the expectation to check for the specific error message when an invalid resource type is provided. * feat: Implement retry logic for MCP server creation to handle race conditions - Enhanced the createMCPServer method to include retry logic with exponential backoff for handling duplicate key errors during concurrent server creation. - Updated tests to verify that all concurrent requests succeed and that unique server names are generated. - Added a helper function to identify MongoDB duplicate key errors, improving error handling during server creation. * refactor: StatusIcon to use CircleCheck for connected status - Replaced the PlugZap icon with CircleCheck in the ConnectedStatusIcon component to better represent the connected state. - Ensured consistent icon usage across the component for improved visual clarity. * test: Update AccessControlService tests to throw errors on invalid resource types - Modified the test for invalid resource types to ensure it throws an error with a specific message instead of returning an empty permissions map. - This change enhances error handling and improves test coverage for the AccessControlService. * fix: Update error message for missing server name in MCP server retrieval - Changed the error message returned when the server name is not provided from 'MCP ID is required' to 'Server name is required' for better clarity and accuracy in the API response. --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Danny Avila <danny@librechat.ai>
2025-12-04 21:37:23 +01:00
/**
* GET /api/permissions/{resourceType}/effective/all
* Get user's effective permissions for all accessible resources of a type
*/
router.get('/:resourceType/effective/all', getAllEffectivePermissions);
/**
* GET /api/permissions/{resourceType}/{resourceId}/effective
* Get user's effective permissions for a specific resource
*/
router.get('/:resourceType/:resourceId/effective', getUserEffectivePermissions);
module.exports = router;