Skip to content

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

🚧 fix: Gate File Search and Run Code by Role (#15691)

Danny Avilaa3fc3b9dbf93
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.js
index 558aba79a9..9bcddc95c9 100644
--- a/api/app/clients/tools/util/handleTools.js
+++ b/api/app/clients/tools/util/handleTools.js
@@ -3,6 +3,8 @@ const { Calculator, createSearchTool, createCodeExecutionTool } = require('@libr
const {
checkAccess,
toolkitParent,
+ toolRolePermissions,
+ checkToolRolePermission,
createSafeUser,
createAuthIdentityContext,
mcpToolPattern,
@@ -347,6 +349,26 @@ const loadTools = async ({
const shadowedServers = findShadowedServerNames(collisionAudit.names);
for (const tool of tools) {
+ /** `loadTools` is the shared boundary for every runtime that equips these
+ * tools — agents, and the Assistants required-action flow via
+ * `processRequiredActions`, which never passes through the agent capability
+ * filter. Gate here so a denied role cannot reach the sandbox or the search
+ * index down any of them. The check is request-cached, so the agent path
+ * that already resolved this grant pays nothing for the second look. */
+ const rolePermission = toolRolePermissions[tool];
+ if (rolePermission != null && options.req?.user != null) {
+ const allowed = await checkToolRolePermission({
+ req: options.req,
+ user: options.req.user,
+ permissionType: rolePermission,
+ getRoleByName,
+ context: 'handleTools',
+ });
+ if (!allowed) {
+ continue;
+ }
+ }
+
if (tool === Tools.execute_code) {
requestedTools[tool] = async () => {
const statefulSessions =
diff --git a/api/app/clients/tools/util/handleTools.rolePermissions.test.js b/api/app/clients/tools/util/handleTools.rolePermissions.test.js
new file mode 100644
index 0000000000..5235bd6165
--- /dev/null
+++ b/api/app/clients/tools/util/handleTools.rolePermissions.test.js
@@ -0,0 +1,138 @@
+/**
+ * `loadTools` is the shared boundary every runtime crosses to equip
+ * `file_search` and `execute_code` — agents, and the Assistants required-action
+ * flow through `processRequiredActions`, which never passes the agent capability
+ * filter. Before this gate, a role with `FILE_SEARCH.USE` or `RUN_CODE.USE` set
+ * to false still got the tool: the permission was stored and served, never
+ * checked.
+ */
+
+const mockGetRoleByName = jest.fn();
+const mockPrimeSearchFiles = jest.fn(async () => ({ files: [], toolContext: undefined }));
+const mockPrimeCodeFiles = jest.fn(async () => ({ files: [], toolContext: undefined }));
+const mockCreateFileSearchTool = jest.fn(async () => ({ name: 'file_search' }));
+const mockCreateCodeExecutionTool = jest.fn(() => ({ name: 'execute_code' }));
+
+jest.mock('@librechat/data-schemas', () => ({
+ ...jest.requireActual('@librechat/data-schemas'),
+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
+}));
+
+jest.mock('@librechat/agents', () => ({
+ ...jest.requireActual('@librechat/agents'),
+ createCodeExecutionTool: (...args) => mockCreateCodeExecutionTool(...args),
+}));
+
+jest.mock('~/models', () => ({
+ ...jest.requireActual('~/models'),
+ getRoleByName: (...args) => mockGetRoleByName(...args),
+}));
+
+jest.mock('~/server/services/Config', () => ({
+ ...jest.requireActual('~/server/services/Config'),
+ checkCapability: jest.fn(async () => false),
+ getMCPServerTools: jest.fn(async () => ({})),
+}));
+
+jest.mock('./fileSearch', () => ({
+ primeFiles: (...args) => mockPrimeSearchFiles(...args),
+ createFileSearchTool: (...args) => mockCreateFileSearchTool(...args),
+}));
+
+jest.mock('~/server/services/Files/Code/process', () => ({
+ primeFiles: (...args) => mockPrimeCodeFiles(...args),
+}));
+
+const { Tools, Permissions, PermissionTypes } = require('librechat-data-provider');
+const { logger } = require('@librechat/data-schemas');
+const { loadTools } = require('./handleTools');
+
+/** Role document shape `checkAccess` reads; both role-gated tools granted. */
+const buildRole = (overrides = {}) => ({
+ name: 'USER',
+ permissions: {
+ [PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
+ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: true },
+ ...overrides,
+ },
+});
+
+const deny = (permissionType) =>
+ mockGetRoleByName.mockResolvedValue(
+ buildRole({ [permissionType]: { [Permissions.USE]: false } }),
+ );
+
+/** `loadTools` takes the request under a nested `options` key — passing `req` at
+ * the top level silently skips every `options.req`-guarded branch. */
+const buildOptions = (tools = [Tools.file_search]) => ({
+ user: 'user-1',
+ tools,
+ options: {
+ req: { user: { id: 'user-1', role: 'USER' }, config: {}, app: { locals: {} } },
+ },
+});
+
+const loadedNames = async (tools) => {
+ const { loadedTools } = await loadTools(buildOptions(tools));
+ return loadedTools.map((tool) => tool.name);
+};
+
+describe('loadTools — tool role permission gate', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockGetRoleByName.mockResolvedValue(buildRole());
+ });
+
+ it('equips file_search when the role permits it', async () => {
+ expect(await loadedNames([Tools.file_search])).toContain(Tools.file_search);
+ });
+
+ it('does not equip file_search when the role denies it', async () => {
+ deny(PermissionTypes.FILE_SEARCH);
+
+ expect(await loadedNames([Tools.file_search])).not.toContain(Tools.file_search);
+ /** The tool must not even be constructed — a denied user should never get a
+ * tool that merely fails later. */
+ expect(mockCreateFileSearchTool).not.toHaveBeenCalled();
+ });
+
+ it('equips execute_code when the role permits it', async () => {
+ expect(await loadedNames([Tools.execute_code])).toContain(Tools.execute_code);
+ });
+
+ /** The Assistants required-action flow reaches this loader directly, so
+ * `RUN_CODE` has to be enforced here and not only on the tool-call route. */
+ it('does not equip execute_code when the role denies it', async () => {
+ deny(PermissionTypes.RUN_CODE);
+
+ expect(await loadedNames([Tools.execute_code])).not.toContain(Tools.execute_code);
+ expect(mockCreateCodeExecutionTool).not.toHaveBeenCalled();
+ });
+
+ it('denies only the tool whose permission is missing', async () => {
+ deny(PermissionTypes.RUN_CODE);
+
+ const names = await loadedNames([Tools.file_search, Tools.execute_code]);
+ expect(names).toContain(Tools.file_search);
+ expect(names).not.toContain(Tools.execute_code);
+ });
+
+ it('logs the denial with the permission type and user', async () => {
+ deny(PermissionTypes.FILE_SEARCH);
+
+ await loadTools(buildOptions([Tools.file_search]));
+
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining(PermissionTypes.FILE_SEARCH));
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('user-1'));
+ });
+
+ it('denies when the role lookup itself throws', async () => {
+ mockGetRoleByName.mockRejectedValue(new Error('role lookup failed'));
+
+ /** Fail closed: an unreachable role store must not hand out the tools. */
+ const names = await loadedNames([Tools.file_search, Tools.execute_code]);
+ expect(names).not.toContain(Tools.file_search);
+ expect(names).not.toContain(Tools.execute_code);
+ expect(logger.error).toHaveBeenCalled();
+ });
+});
diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js
index 5a764ef7cc..494ed4e3b5 100644
--- a/api/server/controllers/agents/__tests__/openai.spec.js
+++ b/api/server/controllers/agents/__tests__/openai.spec.js
@@ -174,6 +174,8 @@ jest.mock('@librechat/agents', () => ({
jest.mock('@librechat/api', () => ({
createAgentExecutionContext: (context) => context,
+ /** Grants both by default; the capability set is what these specs vary. */
+ resolveToolRoleGrants: jest.fn(async () => ({ runCode: true, fileSearch: true })),
collectReachableAgents: (roots) => {
const agents = [];
const pending = [...roots];
diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js
index 31421b3644..31d1eecbad 100644
--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js
+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js
@@ -197,6 +197,8 @@ jest.mock('@librechat/agents', () => ({
jest.mock('@librechat/api', () => ({
createAgentExecutionContext: (context) => context,
+ /** Grants both by default; the capability set is what these specs vary. */
+ resolveToolRoleGrants: jest.fn(async () => ({ runCode: true, fileSearch: true })),
SAFE_CONVERSATION_TITLE: 'New Chat',
resolveConversationTitle: (...args) => mockResolveConversationTitle(...args),
/** Pass-through: the controller strips UI-only activity-label parts
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index b9df554879..b4d29ec2d6 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -148,6 +148,7 @@ const {
resolveRunFadingTiers,
createContextMetaPublisher,
selectRunContextMetaToPublish,
+ resolveToolRoleGrants,
} = require('@librechat/api');
const {
Run,
@@ -2870,6 +2871,19 @@ class AgentClient extends BaseClient {
* tool registered unconditionally; without this passthrough the
* memory path would silently lose code-execution tooling). */
const memoryCapabilities = new Set(appConfig?.endpoints?.[EModelEndpoint.agents]?.capabilities);
+ const memoryCodeEnabled = memoryCapabilities.has(AgentCapabilities.execute_code);
+ /** Same pairing as the chat initializers: the capability is the deployment
+ * switch, the grant is the role's. Skipped when the capability is off, so a
+ * deployment without code execution adds no role read to the shared memory
+ * context. Request-memoized otherwise, so it joins the lookup the tool
+ * loader already made. */
+ const memoryToolGrants = memoryCodeEnabled
+ ? await resolveToolRoleGrants({
+ req: this.options.req,
+ getRoleByName: db.getRoleByName,
+ context: 'memoryAgent',
+ })
+ : null;
const agent = await initializeAgent(
{
req: this.options.req,
@@ -2881,7 +2895,7 @@ class AgentClient extends BaseClient {
? EModelEndpoint.agents
: memoryConfig.agent?.provider,
},
- codeEnvAvailable: memoryCapabilities.has(AgentCapabilities.execute_code),
+ codeEnvAvailable: memoryCodeEnabled && memoryToolGrants?.runCode === true,
statefulSessionsAvailable: memoryCapabilities.has(AgentCapabilities.stateful_code_sessions),
},
{
diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js
index 0706e42cdb..d47c140983 100644
--- a/api/server/controllers/agents/openai.js
+++ b/api/server/controllers/agents/openai.js
@@ -65,6 +65,7 @@ const {
stripActivityLabelParts,
executeAgentRun,
waitForAgentExecutionWrites,
+ resolveToolRoleGrants,
} = require('@librechat/api');
const {
buildSummarizationHandlers,
@@ -489,12 +490,24 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
};
const enabledCapabilities = new Set(agentsEConfig?.capabilities);
+ const codeCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.execute_code);
+ /** Started before the memory read rather than awaited on its own line, so
+ * the role lookup overlaps that query instead of preceding it. Skipped
+ * when the deployment has the capability off — the flag is false either
+ * way, so the read would be pure load on every request. */
+ const toolRoleGrants = codeCapabilityEnabled
+ ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })
+ : null;
const memoryAvailable = await resolveMemoryAvailability({
enabledCapabilities,
memoryConfig: appConfig?.memory,
user: req.user,
getRoleByName: db.getRoleByName,
});
+ /** The deployment switch AND the role grant: `initializeAgent` rebuilds
+ * `bash_tool`, `read_file` and the workspace file tools from this flag,
+ * and forwards the code-environment context to their handlers. */
+ const codeEnvAvailable = codeCapabilityEnabled && (await toolRoleGrants)?.runCode === true;
const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);
const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;
const accessibleSkillIds = skillsCapabilityEnabled
@@ -559,7 +572,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
skillsCapabilityEnabled,
ephemeralSkillsToggle,
}),
- codeEnvAvailable: enabledCapabilities.has(AgentCapabilities.execute_code),
+ codeEnvAvailable,
backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),
toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),
statefulSessionsAvailable: enabledCapabilities.has(
@@ -638,7 +651,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
}),
skillStates,
defaultActiveOnShare,
- codeEnvAvailable: enabledCapabilities.has(AgentCapabilities.execute_code),
+ codeEnvAvailable,
backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),
toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),
statefulSessionsAvailable: enabledCapabilities.has(
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index 0056598338..7ca3581df5 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -80,6 +80,7 @@ const {
CHILD_THREAD_READ_ONLY_ERROR,
executeAgentRun,
waitForAgentExecutionWrites,
+ resolveToolRoleGrants,
} = require('@librechat/api');
const {
createResponsesToolEndCallback,
@@ -736,12 +737,24 @@ const executeResponse = async (envelope, { req, res }) => {
};
const enabledCapabilities = new Set(agentsEConfig?.capabilities);
+ const codeCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.execute_code);
+ /** Started before the memory read rather than awaited on its own line, so
+ * the role lookup overlaps that query instead of preceding it. Skipped
+ * when the deployment has the capability off — the flag is false either
+ * way, so the read would be pure load on every request. */
+ const toolRoleGrants = codeCapabilityEnabled
+ ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })
+ : null;
const memoryAvailable = await resolveMemoryAvailability({
enabledCapabilities,
memoryConfig: appConfig?.memory,
user: req.user,
getRoleByName: db.getRoleByName,
});
+ /** The deployment switch AND the role grant: `initializeAgent` rebuilds
+ * `bash_tool`, `read_file` and the workspace file tools from this flag,
+ * and forwards the code-environment context to their handlers. */
+ const codeEnvAvailable = codeCapabilityEnabled && (await toolRoleGrants)?.runCode === true;
const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);
const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;
const accessibleSkillIds = skillsCapabilityEnabled
@@ -806,7 +819,7 @@ const executeResponse = async (envelope, { req, res }) => {
skillsCapabilityEnabled,
ephemeralSkillsToggle,
}),
- codeEnvAvailable: enabledCapabilities.has(AgentCapabilities.execute_code),
+ codeEnvAvailable,
backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),
toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),
statefulSessionsAvailable: enabledCapabilities.has(
@@ -885,7 +898,7 @@ const executeResponse = async (envelope, { req, res }) => {
}),
skillStates,
defaultActiveOnShare,
- codeEnvAvailable: enabledCapabilities.has(AgentCapabilities.execute_code),
+ codeEnvAvailable,
backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),
toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),
statefulSessionsAvailable: enabledCapabilities.has(
diff --git a/api/server/controllers/assistants/logging.spec.js b/api/server/controllers/assistants/logging.spec.js
index b15020b3de..a66507dabe 100644
--- a/api/server/controllers/assistants/logging.spec.js
+++ b/api/server/controllers/assistants/logging.spec.js
@@ -9,7 +9,9 @@ const mockGetOpenAIClient = jest.fn();
const mockUpdateAssistantDoc = jest.fn();
jest.mock('@librechat/data-schemas', () => ({ logger: mockLogger }));
-jest.mock('@librechat/api', () => ({}));
+jest.mock('@librechat/api', () => ({
+ resolveAssistantToolPermissions: jest.fn(async () => () => true),
+}));
jest.mock('librechat-data-provider', () => ({
FileContext: { avatar: 'avatar' },
ToolCallTypes: {},
diff --git a/api/server/controllers/assistants/v1.js b/api/server/controllers/assistants/v1.js
index 425fb98de8..61a61522cc 100644
--- a/api/server/controllers/assistants/v1.js
+++ b/api/server/controllers/assistants/v1.js
@@ -7,9 +7,15 @@ const {
contentFilterBlockResponse,
contentFilterUninspectableResponse,
getBlockedUninspectableFileField,
+ resolveAssistantToolPermissions,
} = require('@librechat/api');
const { FileContext } = require('librechat-data-provider');
-const { deleteFileByFilter, updateAssistantDoc, getAssistants } = require('~/models');
+const {
+ deleteFileByFilter,
+ updateAssistantDoc,
+ getAssistants,
+ getRoleByName,
+} = require('~/models');
const { uploadImageBuffer, filterFile } = require('~/server/services/Files/process');
const validateAuthor = require('~/server/middleware/assistants/validateAuthor');
const { getStrategyFunctions } = require('~/server/services/Files/strategies');
@@ -53,6 +59,11 @@ const createAssistant = async (req, res) => {
toolDefinitions,
accessibleServerNames,
});
+ const isNativeToolPermitted = await resolveAssistantToolPermissions({
+ req,
+ tools,
+ getRoleByName,
+ });
assistantData.tools = healedTools
.map((tool) => {
@@ -81,7 +92,16 @@ const createAssistant = async (req, res) => {
})
.filter((tool) => tool)
.flat()
- .map(toProviderToolDefinition);
+ .map(toProviderToolDefinition)
+ .filter((tool) => {
+ if (isNativeToolPermitted(tool)) {
+ return true;
+ }
+ logger.warn(
+ `[/assistants] Dropping role-denied native tool from assistant payload: ${tool?.type}`,
+ );
+ return false;
+ });
let azureModelIdentifier = null;
if (openai.locals?.azureOptions) {
@@ -182,6 +202,11 @@ const patchAssistant = async (req, res) => {
toolDefinitions,
accessibleServerNames,
});
+ const isNativeToolPermitted = await resolveAssistantToolPermissions({
+ req,
+ tools: updateData.tools,
+ getRoleByName,
+ });
updateData.tools = healedTools
.map((tool) => {
@@ -210,7 +235,16 @@ const patchAssistant = async (req, res) => {
})
.filter((tool) => tool)
.flat()
- .map(toProviderToolDefinition);
+ .map(toProviderToolDefinition)
+ .filter((tool) => {
+ if (isNativeToolPermitted(tool)) {
+ return true;
+ }
+ logger.warn(
+ `[/assistants] Dropping role-denied native tool from assistant payload: ${tool?.type}`,
+ );
+ return false;
+ });
if (openai.locals?.azureOptions && updateData.model) {
updateData.model = openai.locals.azureOptions.azureOpenAIApiDeploymentName;
diff --git a/api/server/controllers/assistants/v2.js b/api/server/controllers/assistants/v2.js
index 063354d946..74035e6561 100644
--- a/api/server/controllers/assistants/v2.js
+++ b/api/server/controllers/assistants/v2.js
@@ -1,4 +1,5 @@
const { logger } = require('@librechat/data-schemas');
+const { resolveAssistantToolPermissions } = require('@librechat/api');
const { ToolCallTypes } = require('librechat-data-provider');
const validateAuthor = require('~/server/middleware/assistants/validateAuthor');
const { validateAndUpdateTool } = require('~/server/services/ActionService');
@@ -8,7 +9,7 @@ const {
toProviderToolDefinition,
} = require('~/server/services/MCP');
const { manifestToolMap, isAgentsOnlyTool } = require('~/app/clients/tools');
-const { updateAssistantDoc } = require('~/models');
+const { updateAssistantDoc, getRoleByName } = require('~/models');
const { getOpenAIClient } = require('./helpers');
/**
@@ -43,6 +44,11 @@ const createAssistant = async (req, res) => {
toolDefinitions,
accessibleServerNames,
});
+ const isNativeToolPermitted = await resolveAssistantToolPermissions({
+ req,
+ tools,
+ getRoleByName,
+ });
assistantData.tools = healedTools
.map((tool) => {
@@ -71,7 +77,16 @@ const createAssistant = async (req, res) => {
})
.filter((tool) => tool)
.flat()
- .map(toProviderToolDefinition);
+ .map(toProviderToolDefinition)
+ .filter((tool) => {
+ if (isNativeToolPermitted(tool)) {
+ return true;
+ }
+ logger.warn(
+ `[/assistants] Dropping role-denied native tool from assistant payload: ${tool?.type}`,
+ );
+ return false;
+ });
let azureModelIdentifier = null;
if (openai.locals?.azureOptions) {
@@ -163,6 +178,11 @@ const updateAssistant = async ({ req, openai, assistant_id, updateData }) => {
toolDefinitions,
accessibleServerNames,
});
+ const isNativeToolPermitted = await resolveAssistantToolPermissions({
+ req,
+ tools: updateData.tools,
+ getRoleByName,
+ });
for (const tool of healedTools) {
/** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on
* the assistants runtime — drop them even when posted directly, since
@@ -199,6 +219,13 @@ const updateAssistant = async ({ req, openai, assistant_id, updateData }) => {
continue;
}
+ if (!isNativeToolPermitted(actualTool)) {
+ logger.warn(
+ `[/assistants] Dropping role-denied native tool from assistant payload: ${actualTool.type}`,
+ );
+ continue;
+ }
+
if (actualTool.type === ToolCallTypes.FILE_SEARCH) {
hasFileSearch = true;
}
diff --git a/api/server/controllers/tools.js b/api/server/controllers/tools.js
index c2298c5fb4..ac59da27e4 100644
--- a/api/server/controllers/tools.js
+++ b/api/server/controllers/tools.js
@@ -131,7 +131,11 @@ const callTool = async (req, res) => {
logger.debug(`[${toolId}/call] User: ${req.user.id}`);
let hasAccess = true;
if (toolAccessPermType[toolId]) {
+ /** `req` is what puts this read in the request cache, so the shared
+ * `loadTools` gate below resolves the same grant for free instead of
+ * issuing a second serial role lookup before the sandbox call. */
hasAccess = await checkAccess({
+ req,
user: req.user,
permissionType: toolAccessPermType[toolId],
permissions: [Permissions.USE],
diff --git a/api/server/routes/agents/management.js b/api/server/routes/agents/management.js
index 1673c70b77..e339e78e9d 100644
--- a/api/server/routes/agents/management.js
+++ b/api/server/routes/agents/management.js
@@ -19,6 +19,7 @@ const {
ioredisClient,
mapAgentManagementError,
restoreTenantContextFromReq,
+ resolveToolRoleGrants,
} = require('@librechat/api');
const { checkBan, configMiddleware, createFileLimiters } = require('~/server/middleware');
const { hasCapability } = require('~/server/middleware/roles/capabilities');
@@ -95,11 +96,19 @@ const fileHandlers = createAgentManagementFileHandlers({
if (purpose === EToolResources.context) {
return await checkCapability(req, AgentCapabilities.context);
}
+ /** Capability first: a purpose the deployment has switched off is rejected
+ * without a role read. */
if (purpose === EToolResources.execute_code) {
- return await checkCapability(req, AgentCapabilities.execute_code);
+ if (!(await checkCapability(req, AgentCapabilities.execute_code))) {
+ return false;
+ }
+ return (await resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })).runCode;
}
if (purpose === EToolResources.file_search) {
- return await checkCapability(req, AgentCapabilities.file_search);
+ if (!(await checkCapability(req, AgentCapabilities.file_search))) {
+ return false;
+ }
+ return (await resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })).fileSearch;
}
return true;
},
diff --git a/api/server/routes/files/files.js b/api/server/routes/files/files.js
index a945d657e7..f0859b0fb1 100644
--- a/api/server/routes/files/files.js
+++ b/api/server/routes/files/files.js
@@ -18,6 +18,8 @@ const {
assertUploadContentAllowed,
hasActiveFilePolicy,
sanitizeFilename,
+ checkToolResourceUploadPermission,
+ resolveAssistantToolPermissions,
resolveDownloadPath,
} = require('@librechat/api');
const {
@@ -44,6 +46,7 @@ const { fileAccess } = require('~/server/middleware/accessResources/fileAccess')
const { getStrategyFunctions } = require('~/server/services/Files/strategies');
const { getOpenAIClient } = require('~/server/controllers/assistants/helpers');
const { hasCapability } = require('~/server/middleware/roles/capabilities');
+const { getRoleByName } = require('~/models');
const { checkPermission } = require('~/server/services/PermissionService');
const { cleanFileName, getContentDisposition } = require('~/server/utils/files');
const { getLogStores } = require('~/cache');
@@ -726,6 +729,43 @@ router.get('/download/:userId/:file_id', fileAccess, async (req, res) => {
}
});
+/**
+ * A v1 Knowledge upload posts `assistant_id` with no `tool_resource`, so the
+ * resource map has nothing to authorize against. What the file will feed is the
+ * assistant's own native tools, so read those and require their grants.
+ *
+ * Runs here rather than at attach time so a denied role never gets its bytes
+ * into provider storage — an authorization failure after the remote upload
+ * leaves an untracked file behind and reports 500 for what is a 403.
+ *
+ * @returns {Promise<{ ok: boolean, openai?: OpenAI }>} `ok: false` once a
+ * response has been sent. The client it had to build is returned so processing
+ * reuses it rather than re-reading the user's key.
+ */
+const assertLegacyAssistantUploadAllowed = async (req, res, metadata) => {
+ const isLegacyAssistantAttach =
+ isAssistantsEndpoint(metadata.endpoint) &&
+ metadata.assistant_id != null &&
+ !metadata.message_file &&
+ !metadata.tool_resource;
+ if (!isLegacyAssistantAttach) {
+ return { ok: true };
+ }
+
+ const { openai } = await getOpenAIClient({ req });
+ const assistant = await openai.beta.assistants.retrieve(metadata.assistant_id);
+ const isNativeToolPermitted = await resolveAssistantToolPermissions({
+ req,
+ tools: assistant?.tools,
+ getRoleByName,
+ });
+ if ((assistant?.tools ?? []).some((tool) => !isNativeToolPermitted(tool))) {
+ res.status(403).json({ message: 'Forbidden: Insufficient permissions' });
+ return { ok: false };
+ }
+ return { ok: true, openai };
+};
+
const handleFileUpload = async (req, res) => {
const metadata = req.body;
let cleanup = true;
@@ -743,6 +783,22 @@ const handleFileUpload = async (req, res) => {
req.file.originalname = sanitizeFilename(req.file.originalname);
filterFile({ req });
+ /** Check the role permission before any content inspection: a forbidden upload
+ * must be rejected without reading or embedding the file. */
+ const uploadAllowed = await checkToolResourceUploadPermission({
+ req,
+ toolResource: metadata.tool_resource,
+ getRoleByName,
+ });
+ if (!uploadAllowed) {
+ return res.status(403).json({ message: 'Forbidden: Insufficient permissions' });
+ }
+
+ const legacyAssistantUpload = await assertLegacyAssistantUploadAllowed(req, res, metadata);
+ if (!legacyAssistantUpload.ok) {
+ return;
+ }
+
await assertUploadContentAllowed({
filters: req.config?.filters,
file: req.file,
@@ -759,7 +815,13 @@ const handleFileUpload = async (req, res) => {
if (isAssistantsEndpoint(metadata.endpoint)) {
openSseStreamIfRequested();
- return await processFileUpload({ req, res, metadata, sseStream });
+ return await processFileUpload({
+ req,
+ res,
+ metadata,
+ sseStream,
+ openai: legacyAssistantUpload.openai,
+ });
}
let skipUploadAuth = false;
diff --git a/api/server/routes/files/images.js b/api/server/routes/files/images.js
index d2e0c7eef0..1228bddad1 100644
--- a/api/server/routes/files/images.js
+++ b/api/server/routes/files/images.js
@@ -12,6 +12,7 @@ const {
assertUploadContentAllowed,
hasActiveFilePolicy,
sanitizeFilename,
+ checkToolResourceUploadPermission,
} = require('@librechat/api');
const {
isAssistantsEndpoint,
@@ -45,6 +46,18 @@ router.post('/', async (req, res) => {
req.file.originalname = sanitizeFilename(req.file.originalname);
filterFile({ req, image: true });
+ /** The Code Files UI routes image uploads here instead of `/files`, so the
+ * same role gate has to run before any content inspection — otherwise an
+ * image is a way around the tool-resource boundary. */
+ const uploadAllowed = await checkToolResourceUploadPermission({
+ req,
+ toolResource: metadata.tool_resource,
+ getRoleByName: db.getRoleByName,
+ });
+ if (!uploadAllowed) {
+ return res.status(403).json({ message: 'Forbidden: Insufficient permissions' });
+ }
+
await assertUploadContentAllowed({
filters: req.config?.filters,
file: req.file,
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index 98bc05191a..3f29d28d30 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -25,6 +25,7 @@ const {
buildSubagentThreadTaskConfig,
backgroundCompletionWakeupsEnabled,
createLazyAgentHistoryResolver,
+ resolveToolRoleGrants,
} = require('@librechat/api');
const {
ResourceType,
@@ -226,7 +227,15 @@ const initializeClient = async ({
* allowlist with the toggle on = full accessible catalog. */
const enabledCapabilities = new Set(appConfig?.endpoints?.[EModelEndpoint.agents]?.capabilities);
const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);
- const codeEnvAvailable = enabledCapabilities.has(AgentCapabilities.execute_code);
+ const codeCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.execute_code);
+ /** Started here but joined into the startup `Promise.all` below rather than
+ * awaited inline: `codeEnvAvailable` is not read until agent construction, so
+ * the role lookup overlaps the memory, skill and conversation queries instead
+ * of delaying them. Skipped entirely when the deployment has the capability
+ * off, since the flag is false either way. */
+ const toolRoleGrantsPromise = codeCapabilityEnabled
+ ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName, context: 'initializeClient' })
+ : null;
const backgroundToolsAvailable = enabledCapabilities.has(AgentCapabilities.run_in_background);
const toolIntentsAvailable = enabledCapabilities.has(AgentCapabilities.tool_intents);
const deferredToolsAvailable = enabledCapabilities.has(AgentCapabilities.deferred_tools);
@@ -509,6 +518,7 @@ const initializeClient = async ({
{ skillStates, defaultActiveOnShare },
{ primaryAgent, modelsConfig },
requestConversation,
+ toolRoleGrants,
] = await Promise.all([
memoryAvailablePromise,
accessibleSkillIdsPromise,
@@ -517,9 +527,17 @@ const initializeClient = async ({
skillStatesPromise,
validatedPrimaryAgentPromise,
requestConversationPromise,
+ toolRoleGrantsPromise,
]);
delete endpointOption.agent;
+ /** The deployment switch AND the role grant. `initializeAgent` rebuilds
+ * `bash_tool`, `read_file` and the workspace file tools from this flag after
+ * the tool loader has already dropped `execute_code` for a denied role, and
+ * forwards the code-environment context to their handlers — so the grant has
+ * to travel with the flag, not just with the tool list. */
+ const codeEnvAvailable = codeCapabilityEnabled && toolRoleGrants?.runCode === true;
+
const agentConfigs = new Map();
const allowedProviders = new Set(appConfig?.endpoints?.[EModelEndpoint.agents]?.allowedProviders);
diff --git a/api/server/services/Files/process.js b/api/server/services/Files/process.js
index c4fac9bf63..7d8b1e078b 100644
--- a/api/server/services/Files/process.js
+++ b/api/server/services/Files/process.js
@@ -36,6 +36,7 @@ const {
contentFilterBlockResponse,
sweepExpiredFiles: sweepExpiredFilesWithDeps,
startExpiredFileSweep: startExpiredFileSweepWithDeps,
+ resolveToolRoleGrants,
} = require('@librechat/api');
const {
convertImage,
@@ -570,7 +571,12 @@ const uploadImageBuffer = async ({ req, context, metadata = {}, resize = true })
* @param {import('@librechat/api').UploadSseStream | null} [params.sseStream] - Active upload SSE stream, if enabled.
* @returns {Promise<void>}
*/
-const processFileUpload = async ({ req, res, metadata, sseStream }) => {
+/**
+ * @param {OpenAI} [params.openai] - Client the caller already built (the legacy
+ * assistant preflight needs one to authorize). Reused rather than rebuilt, since
+ * constructing it re-reads the user's key.
+ */
+const processFileUpload = async ({ req, res, metadata, sseStream, openai: providedOpenAI }) => {
const appConfig = req.config;
const isAssistantUpload = isAssistantsEndpoint(metadata.endpoint);
const assistantSource =
@@ -581,8 +587,8 @@ const processFileUpload = async ({ req, res, metadata, sseStream }) => {
const { file_id, temp_file_id = null } = metadata;
/** @type {OpenAI | undefined} */
- let openai;
- if (checkOpenAIStorage(source)) {
+ let openai = providedOpenAI;
+ if (openai == null && checkOpenAIStorage(source)) {
({ openai } = await getOpenAIClient({ req }));
}
@@ -606,6 +612,8 @@ const processFileUpload = async ({ req, res, metadata, sseStream }) => {
});
if (isAssistantUpload && !metadata.message_file && !metadata.tool_resource) {
+ /** Authorized at the route before any bytes are sent — see
+ * `assertLegacyAssistantUploadAllowed` in `~/server/routes/files/files`. */
await openai.beta.assistants.files.create(metadata.assistant_id, {
file_id: id,
});
@@ -702,7 +710,10 @@ const processAgentFileUpload = async ({ req, res, metadata, sseStream }) => {
const entity_id = messageAttachment === true ? undefined : agent_id;
const basePath = mime.getType(file.originalname)?.startsWith('image') ? 'images' : 'uploads';
if (tool_resource === EToolResources.execute_code) {
- const isCodeEnabled = await checkCapability(req, AgentCapabilities.execute_code);
+ const isCodeEnabled =
+ (await checkCapability(req, AgentCapabilities.execute_code)) &&
+ (await resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName, context: 'fileUpload' }))
+ .runCode;
if (!isCodeEnabled) {
throw new Error('Code execution is not enabled for Agents');
}
@@ -746,7 +757,10 @@ const processAgentFileUpload = async ({ req, res, metadata, sseStream }) => {
executionProfile: 'default',
});
} else if (tool_resource === EToolResources.file_search) {
- const isFileSearchEnabled = await checkCapability(req, AgentCapabilities.file_search);
+ const isFileSearchEnabled =
+ (await checkCapability(req, AgentCapabilities.file_search)) &&
+ (await resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName, context: 'fileUpload' }))
+ .fileSearch;
if (!isFileSearchEnabled) {
throw new Error('File search is not enabled for Agents');
}
diff --git a/api/server/services/Files/process.spec.js b/api/server/services/Files/process.spec.js
index 90f46f47c3..a69c756e29 100644
--- a/api/server/services/Files/process.spec.js
+++ b/api/server/services/Files/process.spec.js
@@ -102,6 +102,8 @@ jest.mock('@librechat/api', () => {
);
return {
sanitizeFilename: jest.fn((n) => n),
+ /** Grants both; these specs vary the capability set, not the role. */
+ resolveToolRoleGrants: jest.fn(async () => ({ runCode: true, fileSearch: true })),
parseText: jest.fn().mockResolvedValue({ text: '', bytes: 0 }),
processAudioFile: jest.fn(),
extractInspectableFileText: jest.fn(async ({ extract }) => extract()),
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index 6b9fa06e5b..ac67315212 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -54,6 +54,8 @@ const {
LIST_WORKSPACE_FILES_TOOL_NAME,
SEARCH_WORKSPACE_TOOL_NAME,
getTransactionsConfig,
+ checkToolRolePermission,
+ resolveToolRolePermissions,
} = require('@librechat/api');
const {
Time,
@@ -69,6 +71,7 @@ const {
isActionTool,
actionDelimiter,
ImageVisionTool,
+ PermissionTypes,
hasActivePiiFields,
hasActivePiiPatterns,
openapiToFunction,
@@ -107,7 +110,7 @@ const { createOpenIDSessionTokenProvider } = require('~/server/services/OpenIDSe
const { getMCPRequestContext } = require('~/server/services/MCPRequestContext');
const { recordUsage } = require('~/server/services/Threads');
const { loadTools } = require('~/app/clients/tools/util');
-const { findPluginAuthsByKeys } = require('~/models');
+const { findPluginAuthsByKeys, getRoleByName } = require('~/models');
const { getFlowStateManager, getMCPServersRegistry } = require('~/config');
const { getLogStores } = require('~/cache');
@@ -137,6 +140,32 @@ const getActiveToolResources = (toolResources, tools) => {
return Object.keys(activeResources).length > 0 ? activeResources : null;
};
+/** Deployment switch guarding each role-gated tool. Spelled out rather than
+ * inferred from the tool name so the two enums can drift apart safely. */
+const toolCapabilityGates = {
+ [Tools.file_search]: AgentCapabilities.file_search,
+ [Tools.execute_code]: AgentCapabilities.execute_code,
+};
+
+/**
+ * Resolves the role grants for an agent's gated tools. A tool already switched
+ * off by its `AgentCapabilities` entry is skipped, so a disabled deployment
+ * costs no role read and logs no denial.
+ *
+ * @param {ServerRequest} req
+ * @param {string[]} [tools] - The agent's configured tool names.
+ * @param {Set<string>} enabledCapabilities
+ * @returns {Promise<(tool: string) => boolean>} Predicate; `true` for any tool
+ * that carries no role permission.
+ */
+const resolveAgentToolPermissions = (req, tools, enabledCapabilities) =>
+ resolveToolRolePermissions({
+ req,
+ tools,
+ getRoleByName,
+ isEligible: (tool) => enabledCapabilities.has(toolCapabilityGates[tool]),
+ });
+
const assertToolResourcesAllowed = ({ req, toolResources, tools }) => {
const filters = req.config?.filters;
if (filters == null) {
@@ -781,9 +810,14 @@ async function loadToolDefinitionsWrapper({
const actionsEnabled = checkCapability(AgentCapabilities.actions);
const deferredToolsEnabled = checkCapability(AgentCapabilities.deferred_tools);
const programmaticToolsEnabled = enabledCapabilities.has(AgentCapabilities.programmatic_tools);
+ const canUseTool = await resolveAgentToolPermissions(req, agent.tools, enabledCapabilities);
+ /** Gates the sandbox everywhere it is reachable, not just the `execute_code`
+ * entry in `filteredTools`: this flag also drives tool classification and the
+ * programmatic bash tool, which would otherwise run code for a denied role. */
const codeExecutionEnabled =
agent.tools?.includes(Tools.execute_code) === true &&
- enabledCapabilities.has(AgentCapabilities.execute_code);
+ enabledCapabilities.has(AgentCapabilities.execute_code) &&
+ canUseTool(Tools.execute_code);
const resolvedCodeExecutionContext =
codeExecutionContext ??
resolveCodeExecutionContext({
@@ -804,10 +838,10 @@ async function loadToolDefinitionsWrapper({
const filteredTools = agent.tools?.filter((tool) => {
if (tool === Tools.file_search) {
- return checkCapability(AgentCapabilities.file_search);
+ return checkCapability(AgentCapabilities.file_search) && canUseTool(tool);
}
if (tool === Tools.execute_code) {
- return checkCapability(AgentCapabilities.execute_code);
+ return checkCapability(AgentCapabilities.execute_code) && canUseTool(tool);
}
if (tool === Tools.web_search) {
return checkCapability(AgentCapabilities.web_search);
@@ -1575,13 +1609,14 @@ async function loadAgentTools({
const hasMCPTools = agent.tools?.some((tool) => tool?.includes(Constants.mcp_delimiter));
const mcpPermissionContext = createMCPPermissionContext(req);
const canUseMCP = hasMCPTools ? await mcpPermissionContext.canUseServers(req.user) : true;
+ const canUseTool = await resolveAgentToolPermissions(req, agent.tools, enabledCapabilities);
let includesWebSearch = false;
const _agentTools = agent.tools?.filter((tool) => {
if (tool === Tools.file_search) {
- return checkCapability(AgentCapabilities.file_search);
+ return checkCapability(AgentCapabilities.file_search) && canUseTool(tool);
} else if (tool === Tools.execute_code) {
- return checkCapability(AgentCapabilities.execute_code);
+ return checkCapability(AgentCapabilities.execute_code) && canUseTool(tool);
} else if (tool === Tools.web_search) {
includesWebSearch = checkCapability(AgentCapabilities.web_search);
return includesWebSearch;
@@ -1643,7 +1678,8 @@ async function loadAgentTools({
const codeExecutionEnabled =
agent.tools?.includes(Tools.execute_code) === true &&
- enabledCapabilities.has(AgentCapabilities.execute_code);
+ enabledCapabilities.has(AgentCapabilities.execute_code) &&
+ canUseTool(Tools.execute_code);
const statefulCodeSessions =
codeExecutionEnabled &&
enabledCapabilities.has(AgentCapabilities.stateful_code_sessions) &&
@@ -2031,9 +2067,18 @@ async function loadToolsForExecution({
if (actionsEnabled === undefined) {
actionsEnabled = enabledCapabilities.has(AgentCapabilities.actions);
}
+ /** Short-circuits before the role read, so an agent without `execute_code` or a
+ * deployment with the capability off pays nothing for the check. */
const codeExecutionEnabled =
enabledCapabilities?.has(AgentCapabilities.execute_code) === true &&
- agent?.tools?.includes(Tools.execute_code) === true;
+ agent?.tools?.includes(Tools.execute_code) === true &&
+ (await checkToolRolePermission({
+ req,
+ user: req?.user,
+ permissionType: PermissionTypes.RUN_CODE,
+ getRoleByName,
+ context: 'loadToolsForExecution',
+ }));
/** Resolve the trusted endpoint/profile from the actually executing agent.
* This stays per-agent across handoffs and subagents; no graph-global stateful
diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.js
index d0fdf0edf4..0d1a7d1eb7 100644
--- a/api/server/services/__tests__/ToolService.spec.js
+++ b/api/server/services/__tests__/ToolService.spec.js
@@ -5,10 +5,12 @@ const {
Constants,
ResourceType,
ErrorTypes,
+ Permissions,
EToolResources,
EModelEndpoint,
isActionTool,
actionDelimiter,
+ PermissionTypes,
AgentCapabilities,
defaultAgentCapabilities,
} = require('librechat-data-provider');
@@ -128,8 +130,10 @@ jest.mock('../ActionService', () => ({
jest.mock('~/server/services/Threads', () => ({
recordUsage: jest.fn(),
}));
+const mockGetRoleByName = jest.fn();
jest.mock('~/models', () => ({
findPluginAuthsByKeys: jest.fn(),
+ getRoleByName: (...args) => mockGetRoleByName(...args),
}));
jest.mock('~/config', () => ({
getFlowStateManager: jest.fn(() => mockFlowManager),
@@ -170,9 +174,21 @@ const { createOnSearchResults } = require('~/server/services/Tools/search');
const { reinitMCPServer } = require('~/server/services/Tools/mcp');
const { ContentFilterError, PENDING_STALE_MS } = require('@librechat/api');
+/** Role document shape `checkAccess` reads; both role-gated tools granted. */
+function buildRole(overrides = {}) {
+ return {
+ name: 'USER',
+ permissions: {
+ [PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
+ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: true },
+ ...overrides,
+ },
+ };
+}
+
function createMockReq(capabilities) {
return {
- user: { id: 'user_123' },
+ user: { id: 'user_123', role: 'USER' },
config: {
endpoints: {
[EModelEndpoint.agents]: {
@@ -203,6 +219,7 @@ describe('ToolService - Action Capability Gating', () => {
mockGetMCPServerTools.mockResolvedValue(null);
mockGetCachedTools.mockResolvedValue(null);
mockGetUserMCPAuthMap.mockResolvedValue({});
+ mockGetRoleByName.mockResolvedValue(buildRole());
mockGetServerConfig.mockResolvedValue(undefined);
mockFlowManager.getFlowState.mockResolvedValue(undefined);
mockResolveConfigServers.mockResolvedValue({});
@@ -3689,4 +3706,153 @@ describe('ToolService - Action Capability Gating', () => {
expect(callsByName.get(rawNameB).requestBuilder.path).toBe('/items');
});
});
+
+ /**
+ * `AgentCapabilities` is the instance-wide switch; `FILE_SEARCH`/`RUN_CODE` are
+ * the per-role grants. A tool has to clear both, on the definitions path and the
+ * runtime path alike — otherwise a denied user is handed a definition the model
+ * will call and the loader will refuse.
+ */
+ describe('loadAgentTools — tool role permission gating', () => {
+ const capabilities = [
+ AgentCapabilities.tools,
+ AgentCapabilities.file_search,
+ AgentCapabilities.execute_code,
+ ];
+
+ const denyPermission = (deniedType) =>
+ mockGetRoleByName.mockResolvedValue(
+ buildRole({ [deniedType]: { [Permissions.USE]: false } }),
+ );
+
+ beforeEach(() => {
+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities));
+ });
+
+ it('omits file_search from definitions when FILE_SEARCH.USE is denied', async () => {
+ denyPermission(PermissionTypes.FILE_SEARCH);
+
+ await loadAgentTools({
+ req: createMockReq(capabilities),
+ res: {},
+ agent: { id: 'agent_123', tools: [Tools.file_search, Tools.execute_code] },
+ tool_resources: { file_search: { file_ids: ['search-file'] } },
+ definitionsOnly: true,
+ });
+
+ expect(mockLoadToolDefinitions).toHaveBeenCalledTimes(1);
+ const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
+ expect(callArgs.tools).not.toContain(Tools.file_search);
+ expect(callArgs.tools).toContain(Tools.execute_code);
+ });
+
+ it('does not prime search files for a denied user', async () => {
+ denyPermission(PermissionTypes.FILE_SEARCH);
+
+ await loadAgentTools({
+ req: createMockReq(capabilities),
+ res: {},
+ agent: { id: 'agent_123', tools: [Tools.file_search] },
+ tool_resources: { file_search: { file_ids: ['search-file'] } },
+ definitionsOnly: true,
+ });
+
+ expect(mockPrimeSearchFiles).not.toHaveBeenCalled();
+ });
+
+ it('omits file_search from the runtime loader when FILE_SEARCH.USE is denied', async () => {
+ denyPermission(PermissionTypes.FILE_SEARCH);
+
+ await loadAgentTools({
+ req: createMockReq(capabilities),
+ res: {},
+ agent: { id: 'agent_123', tools: [Tools.file_search, Tools.execute_code] },
+ definitionsOnly: false,
+ });
+
+ expect(mockLoadToolsUtil).toHaveBeenCalledTimes(1);
+ const [callArgs] = mockLoadToolsUtil.mock.calls[0];
+ expect(callArgs.tools).not.toContain(Tools.file_search);
+ expect(callArgs.tools).toContain(Tools.execute_code);
+ });
+
+ it('omits execute_code when RUN_CODE.USE is denied', async () => {
+ denyPermission(PermissionTypes.RUN_CODE);
+
+ await loadAgentTools({
+ req: createMockReq(capabilities),
+ res: {},
+ agent: { id: 'agent_123', tools: [Tools.file_search, Tools.execute_code] },
+ tool_resources: { execute_code: { file_ids: ['code-file'] } },
+ definitionsOnly: true,
+ });
+
+ const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
+ expect(callArgs.tools).not.toContain(Tools.execute_code);
+ expect(callArgs.tools).toContain(Tools.file_search);
+ expect(mockPrimeCodeFiles).not.toHaveBeenCalled();
+ });
+
+ /** Dropping `execute_code` from the tool list is not enough: this flag also
+ * reaches tool classification and the programmatic bash tool, either of
+ * which would otherwise run code for a role denied `RUN_CODE`. */
+ it('clears codeExecutionEnabled for the definitions payload when RUN_CODE is denied', async () => {
+ denyPermission(PermissionTypes.RUN_CODE);
+
+ await loadAgentTools({
+ req: createMockReq([...capabilities, AgentCapabilities.programmatic_tools]),
+ res: {},
+ agent: { id: 'agent_123', tools: [Tools.execute_code, 'calculator'] },
+ definitionsOnly: true,
+ });
+
+ const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
+ expect(callArgs.codeExecutionEnabled).toBe(false);
+ });
+
+ it('keeps both tools when the role grants them', async () => {
+ await loadAgentTools({
+ req: createMockReq(capabilities),
+ res: {},
+ agent: { id: 'agent_123', tools: [Tools.file_search, Tools.execute_code] },
+ definitionsOnly: true,
+ });
+
+ const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
+ expect(callArgs.tools).toEqual(
+ expect.arrayContaining([Tools.file_search, Tools.execute_code]),
+ );
+ expect(callArgs.codeExecutionEnabled).toBe(true);
+ });
+
+ it('fails closed when the role lookup throws', async () => {
+ mockGetRoleByName.mockRejectedValue(new Error('role lookup failed'));
+
+ await loadAgentTools({
+ req: createMockReq(capabilities),
+ res: {},
+ agent: { id: 'agent_123', tools: [Tools.file_search, Tools.execute_code, 'calculator'] },
+ definitionsOnly: true,
+ });
+
+ const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
+ expect(callArgs.tools).toEqual(['calculator']);
+ });
+
+ it('skips the permission check when the capability is already disabled', async () => {
+ const toolsOnly = [AgentCapabilities.tools];
+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(toolsOnly));
+
+ await loadAgentTools({
+ req: createMockReq(toolsOnly),
+ res: {},
+ agent: { id: 'agent_123', tools: [Tools.file_search, Tools.execute_code, 'calculator'] },
+ definitionsOnly: true,
+ });
+
+ expect(mockGetRoleByName).not.toHaveBeenCalled();
+ const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
+ expect(callArgs.tools).toEqual(['calculator']);
+ });
+ });
});
diff --git a/api/server/services/__tests__/toolCapabilityGates.spec.js b/api/server/services/__tests__/toolCapabilityGates.spec.js
new file mode 100644
index 0000000000..ccad21b00f
--- /dev/null
+++ b/api/server/services/__tests__/toolCapabilityGates.spec.js
@@ -0,0 +1,113 @@
+const fs = require('fs');
+const path = require('path');
+
+/**
+ * `FILE_SEARCH` and `RUN_CODE` are enforced by pairing each read of the matching
+ * `AgentCapabilities` entry with the role grant from `resolveToolRoleGrants`.
+ * The capability is the deployment switch; the grant is the per-role half. A
+ * read that gets one without the other is a hole — which is how every gap in
+ * this area has been found: a boundary nobody knew existed.
+ *
+ * So the boundary list is pinned here. Adding a read of either capability fails
+ * this test until it is classified below, which is the point: the classification
+ * is the review, and it cannot be skipped by not knowing the site exists.
+ */
+
+const REPO_ROOT = path.resolve(__dirname, '../../../..');
+const SEARCH_ROOTS = ['api/app', 'api/server', 'packages/api/src', 'packages/data-provider/src'];
+const CAPABILITY_PATTERN =
+ /AgentCapabilities\.(execute_code|file_search)\b|EToolResources\.code_interpreter\b/;
+
+/**
+ * Every file holding at least one read, with the count and why each is sound.
+ * Counts rather than line numbers so ordinary edits above a gate don't churn it.
+ */
+const CLASSIFIED = {
+ // -- Gates: capability AND grant --------------------------------------------
+ /** 7 gates + 2 map entries + 2 warning-list entries. */
+ 'api/server/services/ToolService.js': 11,
+ /** `codeEnvAvailable`, paired after the startup batch. */
+ 'api/server/services/Endpoints/agents/initialize.js': 1,
+ /** `codeEnvAvailable` for the OpenAI-compatible route. */
+ 'api/server/controllers/agents/openai.js': 1,
+ /** `codeEnvAvailable` for the Responses route. */
+ 'api/server/controllers/agents/responses.js': 1,
+ /** `codeEnvAvailable` for the memory-agent initializer. */
+ 'api/server/controllers/agents/client.js': 1,
+ /** Upload processing: the code-environment and file-search branches. */
+ 'api/server/services/Files/process.js': 2,
+ /** Agent-management upload purposes. */
+ 'api/server/routes/agents/management.js': 2,
+ /** One gate, paired when the embedder wires `getRoleByName`; one in a comment. */
+ 'packages/api/src/agents/openai/service.ts': 2,
+
+ // -- Not gates ---------------------------------------------------------------
+ /** The upload-resource map entry, and one mention in a doc comment. */
+ 'packages/api/src/tools/rolePermissions.ts': 2,
+ /** `recordCapabilityToolNames` bookkeeping — describes what was built, does
+ * not decide whether to build it. */
+ 'packages/api/src/agents/initialize.ts': 2,
+ /** Default capability list shipped in config. */
+ 'packages/data-provider/src/config.ts': 2,
+ /** Config normalization only: strips stale `tool_options` when the capability
+ * is off. Execution is gated by the loaders, so this needs no grant. */
+ 'api/server/controllers/agents/v1.js': 1,
+};
+
+/** @returns {string[]} repo-relative files under `dir`, excluding tests. */
+function walk(dir) {
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
+ return entries.flatMap((entry) => {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ return entry.name === 'node_modules' || entry.name === 'dist' ? [] : walk(full);
+ }
+ if (!/\.(js|ts)$/.test(entry.name) || /\.(test|spec)\.[jt]s$/.test(entry.name)) {
+ return [];
+ }
+ return [full];
+ });
+}
+
+function collectReads() {
+ const found = {};
+ for (const root of SEARCH_ROOTS) {
+ for (const file of walk(path.join(REPO_ROOT, root))) {
+ const matches = fs
+ .readFileSync(file, 'utf8')
+ .split('\n')
+ .filter((line) => CAPABILITY_PATTERN.test(line));
+ if (matches.length > 0) {
+ found[path.relative(REPO_ROOT, file)] = matches.length;
+ }
+ }
+ }
+ return found;
+}
+
+describe('FILE_SEARCH / RUN_CODE capability reads are all classified', () => {
+ const found = collectReads();
+
+ it('has no unclassified file reading a role-gated capability', () => {
+ const unclassified = Object.keys(found)
+ .filter((file) => CLASSIFIED[file] == null)
+ .sort();
+
+ expect({
+ unclassified,
+ hint: 'A new read of AgentCapabilities.execute_code / file_search or EToolResources.code_interpreter. Pair it with resolveToolRoleGrants, then record it in CLASSIFIED with why it is sound.',
+ }).toEqual({ unclassified: [], hint: expect.any(String) });
+ });
+
+ it('has no classified file whose read count drifted', () => {
+ const drifted = Object.entries(CLASSIFIED)
+ .filter(([file, expected]) => (found[file] ?? 0) !== expected)
+ .map(([file, expected]) => `${file}: expected ${expected}, found ${found[file] ?? 0}`)
+ .sort();
+
+ expect({
+ drifted,
+ hint: 'A capability read was added or removed. If added, pair it with the grant before updating the count.',
+ }).toEqual({ drifted: [], hint: expect.any(String) });
+ });
+});
diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts
index 8d58ab35e9..64d59e8422 100644
--- a/packages/api/src/agents/initialize.ts
+++ b/packages/api/src/agents/initialize.ts
@@ -1016,6 +1016,12 @@ export async function initializeAgent(
if (conversationId != null && resendFiles) {
const toolResourceSet = new Set<EToolResources>();
for (const tool of agent.tools ?? []) {
+ /** `effectiveCodeEnvAvailable` already carries the role grant, so a denied
+ * role skips the thread walk and the code-file hydration below rather
+ * than paying for resources the tool loader is about to drop. */
+ if (tool === Tools.execute_code && !effectiveCodeEnvAvailable) {
+ continue;
+ }
if (EToolResources[tool as keyof typeof EToolResources]) {
toolResourceSet.add(EToolResources[tool as keyof typeof EToolResources]);
}
diff --git a/packages/api/src/agents/openai/service.ts b/packages/api/src/agents/openai/service.ts
index eb5e7ddad7..92243b040c 100644
--- a/packages/api/src/agents/openai/service.ts
+++ b/packages/api/src/agents/openai/service.ts
@@ -72,6 +72,7 @@ import {
} from '~/middleware/modelBoundContent';
import { contentFilterBlockResponse, isContentFilterError } from '~/middleware/contentFilter';
import { contentFilterUninspectableResponse } from '~/protection/files';
+import { resolveToolRoleGrants } from '../../tools/rolePermissions';
import { createMCPRuntimeRequestBody } from '~/mcp/request';
import { getUserFacingProviderError } from '../errors';
import { collectReachableAgents } from '../traversal';
@@ -119,6 +120,12 @@ export interface ChatCompletionDependencies {
* keep tenant tracing and code execution working.
*/
appConfig?: AppConfig;
+ /**
+ * Supply to have `codeEnvAvailable` respect the caller's `RUN_CODE` grant as
+ * well as the deployment capability. Optional so existing embedders keep
+ * their current behavior; without it this route is gated by capability alone.
+ */
+ getRoleByName?: Parameters<typeof resolveToolRoleGrants>[0]['getRoleByName'];
/** Tool execute options for event-driven tool execution */
toolExecuteOptions?: ToolExecuteOptions;
}
@@ -668,7 +675,15 @@ export async function createAgentChatCompletion(
agentsConfig != null && typeof agentsConfig === 'object'
? ((agentsConfig as { capabilities?: string[] }).capabilities ?? []).includes(capability)
: undefined;
- const codeEnvAvailable = capabilityEnabled(AgentCapabilities.execute_code);
+ const capabilityAllowsCodeEnv = capabilityEnabled(AgentCapabilities.execute_code);
+ /** Paired with the role grant when the embedder wires `getRoleByName`;
+ * `initializeAgent` rebuilds `bash_tool`, `read_file` and the workspace
+ * file tools from this flag, so a denied role would otherwise keep the
+ * code environment's file handlers. */
+ const codeEnvAvailable =
+ capabilityAllowsCodeEnv === true && deps.getRoleByName != null
+ ? (await resolveToolRoleGrants({ req, getRoleByName: deps.getRoleByName })).runCode
+ : capabilityAllowsCodeEnv;
/** Mirror `codeEnvAvailable` for the stateful-session gate so this route
* also carries each agent's trusted stateful endpoint/profile selection
* into tool loading and prewarming. */
diff --git a/packages/api/src/tools/index.ts b/packages/api/src/tools/index.ts
index d14df15df4..d48daea26b 100644
--- a/packages/api/src/tools/index.ts
+++ b/packages/api/src/tools/index.ts
@@ -4,3 +4,4 @@ export * from './registry';
export * from './toolkits';
export * from './definitions';
export * from './classification';
+export * from './rolePermissions';
diff --git a/packages/api/src/tools/rolePermissions.spec.ts b/packages/api/src/tools/rolePermissions.spec.ts
new file mode 100644
index 0000000000..1716133808
--- /dev/null
+++ b/packages/api/src/tools/rolePermissions.spec.ts
@@ -0,0 +1,343 @@
+import { Tools, Permissions, EToolResources, PermissionTypes } from 'librechat-data-provider';
+import type { Request as ServerRequest } from 'express';
+import type { IRole } from '@librechat/data-schemas';
+import {
+ toolRolePermissions,
+ checkToolRolePermission,
+ resolveToolRolePermissions,
+ toolResourceRolePermissions,
+ assistantToolRolePermissions,
+ resolveToolRoleGrants,
+ resolveAssistantToolPermissions,
+ checkToolResourceUploadPermission,
+} from './rolePermissions';
+
+const buildRole = (overrides: Record<string, unknown> = {}) =>
+ ({
+ name: 'USER',
+ permissions: {
+ [PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
+ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: true },
+ ...overrides,
+ },
+ }) as unknown as IRole;
+
+const buildReq = () => ({ user: { id: 'user_1', role: 'USER' } }) as unknown as ServerRequest;
+
+describe('tool role permission maps', () => {
+ it('covers both role-gated agent tools', () => {
+ expect(toolRolePermissions[Tools.file_search]).toBe(PermissionTypes.FILE_SEARCH);
+ expect(toolRolePermissions[Tools.execute_code]).toBe(PermissionTypes.RUN_CODE);
+ });
+
+ /** The Assistants builder uploads under `code_interpreter`, not `execute_code`,
+ * so leaving it out reopens the upload half of the RUN_CODE door. */
+ it('maps every code-bearing tool resource to RUN_CODE', () => {
+ expect(toolResourceRolePermissions[EToolResources.execute_code]).toBe(PermissionTypes.RUN_CODE);
+ expect(toolResourceRolePermissions[EToolResources.code_interpreter]).toBe(
+ PermissionTypes.RUN_CODE,
+ );
+ expect(toolResourceRolePermissions[EToolResources.file_search]).toBe(
+ PermissionTypes.FILE_SEARCH,
+ );
+ });
+
+ /** The v1 builder submits `retrieval` for the same capability v2 calls
+ * `file_search`; missing it leaves legacy assistants ungated. */
+ it('maps native assistant tool types, both spellings of file search', () => {
+ expect(assistantToolRolePermissions['code_interpreter']).toBe(PermissionTypes.RUN_CODE);
+ expect(assistantToolRolePermissions['file_search']).toBe(PermissionTypes.FILE_SEARCH);
+ expect(assistantToolRolePermissions['retrieval']).toBe(PermissionTypes.FILE_SEARCH);
+ });
+});
+
+describe('checkToolRolePermission', () => {
+ it('grants when the role carries the permission', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+
+ await expect(
+ checkToolRolePermission({
+ req: buildReq(),
+ user: buildReq().user as never,
+ permissionType: PermissionTypes.RUN_CODE,
+ getRoleByName,
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it('denies when the role withholds it', async () => {
+ const getRoleByName = jest
+ .fn()
+ .mockResolvedValue(buildRole({ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: false } }));
+
+ await expect(
+ checkToolRolePermission({
+ req: buildReq(),
+ user: buildReq().user as never,
+ permissionType: PermissionTypes.RUN_CODE,
+ getRoleByName,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ /** Default: a denial blocks the operation, so an unreachable role store must
+ * deny rather than let the request through. */
+ it('fails closed when the role lookup throws', async () => {
+ const getRoleByName = jest.fn().mockRejectedValue(new Error('unreachable'));
+
+ await expect(
+ checkToolRolePermission({
+ req: buildReq(),
+ user: buildReq().user as never,
+ permissionType: PermissionTypes.FILE_SEARCH,
+ getRoleByName,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it('rethrows for callers that mutate rather than block', async () => {
+ const getRoleByName = jest.fn().mockRejectedValue(new Error('unreachable'));
+
+ await expect(
+ checkToolRolePermission({
+ req: buildReq(),
+ user: buildReq().user as never,
+ permissionType: PermissionTypes.FILE_SEARCH,
+ getRoleByName,
+ throwOnError: true,
+ }),
+ ).rejects.toThrow('unreachable');
+ });
+
+ it('fails closed without a user', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+
+ await expect(
+ checkToolRolePermission({
+ permissionType: PermissionTypes.FILE_SEARCH,
+ getRoleByName,
+ }),
+ ).resolves.toBe(false);
+ expect(getRoleByName).not.toHaveBeenCalled();
+ });
+});
+
+describe('resolveToolRolePermissions', () => {
+ it('passes tools that carry no role permission', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+ const canUse = await resolveToolRolePermissions({
+ req: buildReq(),
+ tools: ['calculator'],
+ getRoleByName,
+ });
+
+ expect(canUse('calculator')).toBe(true);
+ expect(getRoleByName).not.toHaveBeenCalled();
+ });
+
+ it('denies only the tool whose grant is missing', async () => {
+ const getRoleByName = jest
+ .fn()
+ .mockResolvedValue(buildRole({ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: false } }));
+ const canUse = await resolveToolRolePermissions({
+ req: buildReq(),
+ tools: [Tools.file_search, Tools.execute_code],
+ getRoleByName,
+ });
+
+ expect(canUse(Tools.file_search)).toBe(true);
+ expect(canUse(Tools.execute_code)).toBe(false);
+ });
+
+ /** Two gated tools on one request must not cost two role reads. */
+ it('reads the role once per request', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+ await resolveToolRolePermissions({
+ req: buildReq(),
+ tools: [Tools.file_search, Tools.execute_code],
+ getRoleByName,
+ });
+
+ expect(getRoleByName).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips tools the caller marks ineligible', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+ const canUse = await resolveToolRolePermissions({
+ req: buildReq(),
+ tools: [Tools.file_search],
+ getRoleByName,
+ isEligible: () => false,
+ });
+
+ expect(getRoleByName).not.toHaveBeenCalled();
+ expect(canUse(Tools.file_search)).toBe(true);
+ });
+});
+
+describe('checkToolResourceUploadPermission', () => {
+ it('allows a resource that carries no role permission', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+
+ await expect(
+ checkToolResourceUploadPermission({
+ req: buildReq(),
+ toolResource: EToolResources.context,
+ getRoleByName,
+ }),
+ ).resolves.toBe(true);
+ expect(getRoleByName).not.toHaveBeenCalled();
+ });
+
+ it('allows an upload with no tool resource at all', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+
+ await expect(
+ checkToolResourceUploadPermission({ req: buildReq(), getRoleByName }),
+ ).resolves.toBe(true);
+ });
+
+ /** The Code Files UI posts images under `execute_code` through a separate
+ * handler, so both upload routes have to reach the same verdict. */
+ it('denies a code-bearing upload when RUN_CODE is withheld', async () => {
+ const getRoleByName = jest
+ .fn()
+ .mockResolvedValue(buildRole({ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: false } }));
+
+ await expect(
+ checkToolResourceUploadPermission({
+ req: buildReq(),
+ toolResource: EToolResources.execute_code,
+ getRoleByName,
+ }),
+ ).resolves.toBe(false);
+ await expect(
+ checkToolResourceUploadPermission({
+ req: buildReq(),
+ toolResource: EToolResources.code_interpreter,
+ getRoleByName,
+ }),
+ ).resolves.toBe(false);
+ });
+});
+
+describe('resolveAssistantToolPermissions', () => {
+ it('keeps native tools the role grants', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+ const permitted = await resolveAssistantToolPermissions({
+ req: buildReq(),
+ tools: [{ type: 'code_interpreter' }, { type: 'file_search' }],
+ getRoleByName,
+ });
+
+ expect(permitted({ type: 'code_interpreter' })).toBe(true);
+ expect(permitted({ type: 'file_search' })).toBe(true);
+ });
+
+ it('drops only the native tool whose grant is missing', async () => {
+ const getRoleByName = jest
+ .fn()
+ .mockResolvedValue(buildRole({ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: false } }));
+ const permitted = await resolveAssistantToolPermissions({
+ req: buildReq(),
+ tools: [{ type: 'code_interpreter' }, { type: 'file_search' }],
+ getRoleByName,
+ });
+
+ expect(permitted({ type: 'code_interpreter' })).toBe(false);
+ expect(permitted({ type: 'file_search' })).toBe(true);
+ });
+
+ it('drops legacy v1 retrieval when FILE_SEARCH is withheld', async () => {
+ const getRoleByName = jest
+ .fn()
+ .mockResolvedValue(
+ buildRole({ [PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: false } }),
+ );
+ const permitted = await resolveAssistantToolPermissions({
+ req: buildReq(),
+ tools: [{ type: 'retrieval' }],
+ getRoleByName,
+ });
+
+ expect(permitted({ type: 'retrieval' })).toBe(false);
+ });
+
+ /** A denial here filters a payload the writers then persist, so an outage
+ * must abort the write rather than read as "not permitted" — otherwise a
+ * transient role-database failure permanently strips an assistant's tools. */
+ it('propagates a failed role lookup instead of reporting a denial', async () => {
+ const getRoleByName = jest.fn().mockRejectedValue(new Error('role store unreachable'));
+
+ await expect(
+ resolveAssistantToolPermissions({
+ req: buildReq(),
+ tools: [{ type: 'code_interpreter' }],
+ getRoleByName,
+ }),
+ ).rejects.toThrow('role store unreachable');
+ });
+
+ it('never drops function tools, which carry no native grant', async () => {
+ const getRoleByName = jest
+ .fn()
+ .mockResolvedValue(buildRole({ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: false } }));
+ const permitted = await resolveAssistantToolPermissions({
+ req: buildReq(),
+ tools: [{ type: 'code_interpreter' }],
+ getRoleByName,
+ });
+
+ expect(permitted({ type: 'function' })).toBe(true);
+ expect(permitted('calculator')).toBe(true);
+ expect(permitted(undefined)).toBe(true);
+ });
+});
+
+describe('resolveToolRoleGrants', () => {
+ it('reports both grants from one role read', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+
+ await expect(resolveToolRoleGrants({ req: buildReq(), getRoleByName })).resolves.toEqual({
+ runCode: true,
+ fileSearch: true,
+ });
+ expect(getRoleByName).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports each grant independently', async () => {
+ const getRoleByName = jest
+ .fn()
+ .mockResolvedValue(buildRole({ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: false } }));
+
+ await expect(resolveToolRoleGrants({ req: buildReq(), getRoleByName })).resolves.toEqual({
+ runCode: false,
+ fileSearch: true,
+ });
+ });
+
+ /** The whole point of centralizing: several gates on one request must not
+ * each pay their own role lookup. */
+ it('memoizes on the request across repeat callers', async () => {
+ const getRoleByName = jest.fn().mockResolvedValue(buildRole());
+ const req = buildReq();
+
+ const [first, second] = await Promise.all([
+ resolveToolRoleGrants({ req, getRoleByName }),
+ resolveToolRoleGrants({ req, getRoleByName }),
+ ]);
+ await resolveToolRoleGrants({ req, getRoleByName });
+
+ expect(first).toBe(second);
+ expect(getRoleByName).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails both grants closed when the role lookup throws', async () => {
+ const getRoleByName = jest.fn().mockRejectedValue(new Error('unreachable'));
+
+ await expect(resolveToolRoleGrants({ req: buildReq(), getRoleByName })).resolves.toEqual({
+ runCode: false,
+ fileSearch: false,
+ });
+ });
+});
diff --git a/packages/api/src/tools/rolePermissions.ts b/packages/api/src/tools/rolePermissions.ts
new file mode 100644
index 0000000000..2b8185a2bd
--- /dev/null
+++ b/packages/api/src/tools/rolePermissions.ts
@@ -0,0 +1,313 @@
+import { logger } from '@librechat/data-schemas';
+import {
+ Tools,
+ Permissions,
+ EToolResources,
+ ToolCallTypes,
+ PermissionTypes,
+} from 'librechat-data-provider';
+import type { Request as ServerRequest } from 'express';
+import type { CheckAccessParams } from '../middleware/access';
+import { checkAccessWithRequestCache } from '../middleware/access';
+
+/**
+ * Role permission that gates a built-in agent tool. The matching
+ * `AgentCapabilities` entry is the instance-wide deployment switch; this is the
+ * per-role grant, so a tool has to clear both.
+ */
+export const toolRolePermissions: Partial<Record<string, PermissionTypes>> = {
+ [Tools.file_search]: PermissionTypes.FILE_SEARCH,
+ [Tools.execute_code]: PermissionTypes.RUN_CODE,
+};
+
+/**
+ * Role permission required to upload for a given tool resource — the other half
+ * of the same door as {@link toolRolePermissions}. `code_interpreter` is the
+ * Assistants-side name for the same capability `execute_code` covers on agents.
+ */
+export const toolResourceRolePermissions: Partial<Record<string, PermissionTypes>> = {
+ [EToolResources.file_search]: PermissionTypes.FILE_SEARCH,
+ [EToolResources.execute_code]: PermissionTypes.RUN_CODE,
+ [EToolResources.code_interpreter]: PermissionTypes.RUN_CODE,
+};
+
+/**
+ * Role permission that gates a native Assistants tool by its provider-side
+ * `type`. These run inside the provider, never through the agent tool loaders,
+ * so they have to be gated where the assistant is configured.
+ */
+export const assistantToolRolePermissions: Partial<Record<string, PermissionTypes>> = {
+ [ToolCallTypes.FILE_SEARCH]: PermissionTypes.FILE_SEARCH,
+ /** The v1 builder submits `retrieval` where v2 submits `file_search`; both are
+ * the same provider capability, so both answer to the same grant. */
+ [ToolCallTypes.RETRIEVAL]: PermissionTypes.FILE_SEARCH,
+ [ToolCallTypes.CODE_INTERPRETER]: PermissionTypes.RUN_CODE,
+};
+
+export interface CheckToolRolePermissionParams {
+ req?: ServerRequest;
+ user?: CheckAccessParams['user'] | null;
+ permissionType: PermissionTypes;
+ getRoleByName: CheckAccessParams['getRoleByName'];
+ /** Prefix for the denial log line, e.g. `loadAgentTools`. */
+ context?: string;
+ /**
+ * Rethrow when the role lookup itself fails, instead of reporting a denial.
+ *
+ * Denying on error is right where a denial blocks the operation. It is wrong
+ * where a denial instead *filters* a payload the caller then persists: there,
+ * a transient outage would silently strip an assistant's native tools and save
+ * the result. Callers that mutate pass this so the write aborts instead.
+ */
+ throwOnError?: boolean;
+}
+
+/**
+ * Resolves a single `USE` grant through the per-request permission cache, so
+ * repeat checks within one request cost no extra role read.
+ *
+ * Fails closed: a missing user or a check that throws denies the tool.
+ */
+export async function checkToolRolePermission({
+ req,
+ user,
+ permissionType,
+ getRoleByName,
+ context = 'toolRolePermissions',
+ throwOnError = false,
+}: CheckToolRolePermissionParams): Promise<boolean> {
+ let allowed = false;
+ try {
+ allowed = await checkAccessWithRequestCache({
+ req,
+ user: user as CheckAccessParams['user'],
+ permissionType,
+ permissions: [Permissions.USE],
+ getRoleByName,
+ });
+ } catch (error) {
+ logger.error(`[${context}][User: ${user?.id}] Failed ${permissionType} permission check`);
+ if (throwOnError) {
+ throw error;
+ }
+ }
+
+ if (!allowed) {
+ logger.warn(
+ `[${permissionType}] Forbidden: Insufficient permissions for User ${user?.id}: ${Permissions.USE}`,
+ );
+ }
+
+ return allowed;
+}
+
+export interface ResolveToolRolePermissionsParams {
+ req?: ServerRequest;
+ /** Tool names as configured on the agent. */
+ tools?: string[] | null;
+ getRoleByName: CheckAccessParams['getRoleByName'];
+ /**
+ * Optional pre-filter. Tools this rejects are never checked, so a tool already
+ * turned off by its `AgentCapabilities` switch costs no role read and logs no
+ * denial.
+ */
+ isEligible?: (tool: string) => boolean;
+ context?: string;
+}
+
+/**
+ * Resolves role permissions for the gated tools an agent actually requests and
+ * returns a synchronous predicate, so a capability filter can consult the result
+ * inline. Tools carrying no role permission always pass.
+ */
+export async function resolveToolRolePermissions({
+ req,
+ tools,
+ getRoleByName,
+ isEligible,
+ context = 'loadAgentTools',
+}: ResolveToolRolePermissionsParams): Promise<(tool: string) => boolean> {
+ const gated = new Set(
+ (tools ?? []).filter(
+ (tool) => toolRolePermissions[tool] != null && (isEligible?.(tool) ?? true),
+ ),
+ );
+ if (gated.size === 0) {
+ return () => true;
+ }
+
+ const granted = new Map<string, boolean>();
+ for (const tool of gated) {
+ granted.set(
+ tool,
+ await checkToolRolePermission({
+ req,
+ user: req?.user as CheckAccessParams['user'],
+ permissionType: toolRolePermissions[tool] as PermissionTypes,
+ getRoleByName,
+ context,
+ }),
+ );
+ }
+
+ return (tool: string) => granted.get(tool) ?? true;
+}
+
+export interface CheckToolResourceUploadParams {
+ req?: ServerRequest;
+ /** `tool_resource` as posted by the client. */
+ toolResource?: string | null;
+ getRoleByName: CheckAccessParams['getRoleByName'];
+}
+
+/**
+ * Authorizes an upload destined for a role-gated tool resource. Shared by every
+ * upload handler that accepts `tool_resource` — the ordinary `/files` route and
+ * `/files/images`, which routes agent uploads of its own.
+ *
+ * Resolves to `allowed` for a resource that carries no role permission.
+ */
+export async function checkToolResourceUploadPermission({
+ req,
+ toolResource,
+ getRoleByName,
+}: CheckToolResourceUploadParams): Promise<boolean> {
+ const permissionType = toolResource != null ? toolResourceRolePermissions[toolResource] : null;
+ if (permissionType == null) {
+ return true;
+ }
+
+ return await checkToolRolePermission({
+ req,
+ user: req?.user as CheckAccessParams['user'],
+ permissionType,
+ getRoleByName,
+ context: 'upload',
+ });
+}
+
+export interface ResolveAssistantToolPermissionsParams {
+ req?: ServerRequest;
+ /** Tools as posted: names, or provider definitions carrying a `type`. */
+ tools?: Array<string | { type?: string } | null | undefined> | null;
+ getRoleByName: CheckAccessParams['getRoleByName'];
+}
+
+/**
+ * Resolves which native Assistants tools the role may configure, and returns a
+ * synchronous predicate for filtering a tool payload.
+ *
+ * Native tools run inside the provider and never reach the agent tool loaders,
+ * so the assistant writers are where they have to be gated.
+ *
+ * Every caller either persists the filtered payload or rejects the request, so a
+ * role lookup that fails propagates rather than reporting a denial: treating an
+ * outage as "not permitted" here would quietly strip an assistant's native tools
+ * and save that as its new configuration.
+ */
+export async function resolveAssistantToolPermissions({
+ req,
+ tools,
+ getRoleByName,
+}: ResolveAssistantToolPermissionsParams): Promise<
+ (tool: string | { type?: string } | null | undefined) => boolean
+> {
+ const toolType = (tool: string | { type?: string } | null | undefined) =>
+ typeof tool === 'string' ? tool : tool?.type;
+ const requested = new Set(
+ (tools ?? [])
+ .map(toolType)
+ .filter((type): type is string => type != null && assistantToolRolePermissions[type] != null),
+ );
+ if (requested.size === 0) {
+ return () => true;
+ }
+
+ const denied = new Set<string>();
+ for (const type of requested) {
+ const allowed = await checkToolRolePermission({
+ req,
+ user: req?.user as CheckAccessParams['user'],
+ permissionType: assistantToolRolePermissions[type] as PermissionTypes,
+ getRoleByName,
+ context: 'assistants',
+ throwOnError: true,
+ });
+ if (!allowed) {
+ denied.add(type);
+ }
+ }
+
+ return (tool) => {
+ const type = toolType(tool);
+ return type == null || !denied.has(type);
+ };
+}
+
+/** Memoizes the resolved grants for the lifetime of one request. */
+const toolRoleGrantsKey = Symbol.for('librechat.toolRoleGrants');
+
+export interface ToolRoleGrants {
+ /** `RUN_CODE.USE` — the sandbox, its file tools, and PTC. */
+ runCode: boolean;
+ /** `FILE_SEARCH.USE` — the search tool and its uploads. */
+ fileSearch: boolean;
+}
+
+export interface ResolveToolRoleGrantsParams {
+ req?: ServerRequest;
+ getRoleByName: CheckAccessParams['getRoleByName'];
+ context?: string;
+}
+
+/**
+ * Resolves both tool grants for a request, once.
+ *
+ * Every gate on `AgentCapabilities.execute_code` / `file_search` reads its role
+ * half from here, so a boundary is authorized by pairing the capability with a
+ * field of this object rather than by repeating a permission check. The two
+ * lookups run together and the result is memoized on the request, so a startup
+ * that consults several gates — the tool loader, the agent initializer, an
+ * upload handler — pays one role read between them.
+ *
+ * Callers that want the read off their critical path can start it early without
+ * awaiting; the memoized promise is what later callers join.
+ *
+ * Fails closed: a missing user or a check that throws denies both.
+ */
+export function resolveToolRoleGrants({
+ req,
+ getRoleByName,
+ context = 'toolRoleGrants',
+}: ResolveToolRoleGrantsParams): Promise<ToolRoleGrants> {
+ const cache = req as
+ | (ServerRequest & { [toolRoleGrantsKey]?: Promise<ToolRoleGrants> })
+ | undefined;
+ const memoized = cache?.[toolRoleGrantsKey];
+ if (memoized) {
+ return memoized;
+ }
+
+ const pending = Promise.all([
+ checkToolRolePermission({
+ req,
+ user: req?.user as CheckAccessParams['user'],
+ permissionType: PermissionTypes.RUN_CODE,
+ getRoleByName,
+ context,
+ }),
+ checkToolRolePermission({
+ req,
+ user: req?.user as CheckAccessParams['user'],
+ permissionType: PermissionTypes.FILE_SEARCH,
+ getRoleByName,
+ context,
+ }),
+ ]).then(([runCode, fileSearch]) => ({ runCode, fileSearch }));
+
+ if (cache) {
+ Object.defineProperty(cache, toolRoleGrantsKey, { value: pending, enumerable: false });
+ }
+
+ return pending;
+}